package com.mdd.front.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.OrderUrgeMsg;
import com.mdd.common.entity.RefundLog;
import com.mdd.common.entity.RefundRecord;
import com.mdd.common.entity.Shop;
import com.mdd.common.entity.VipRecord;
import com.mdd.common.entity.cart.Cart;
import com.mdd.common.entity.coupon.Coupon;
import com.mdd.common.entity.coupon.CouponList;
import com.mdd.common.entity.delivery.ExpressCompany;
import com.mdd.common.entity.delivery.ExpressTpl;
import com.mdd.common.entity.distribution.Distribution;
import com.mdd.common.entity.distribution.DistributionLevel;
import com.mdd.common.entity.distribution.DistributionOrder;
import com.mdd.common.entity.goods.Goods;
import com.mdd.common.entity.goods.GoodsSku;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.order.OrderAfter;
import com.mdd.common.entity.order.OrderAfterGoods;
import com.mdd.common.entity.order.OrderGoods;
import com.mdd.common.entity.seckill.SeckillActivity;
import com.mdd.common.entity.seckill.SeckillGoodsSku;
import com.mdd.common.entity.user.User;
import com.mdd.common.enums.CouponEnum;
import com.mdd.common.enums.DistributionEnum;
import com.mdd.common.enums.LogMoneyEnum;
import com.mdd.common.enums.LogOrderAfterEnum;
import com.mdd.common.enums.OrderAfterEnum;
import com.mdd.common.enums.OrderEnum;
import com.mdd.common.enums.OrderGoodsEnum;
import com.mdd.common.enums.OrderLogEnum;
import com.mdd.common.enums.PaymentEnum;
import com.mdd.common.enums.RefundEnum;
import com.mdd.common.enums.SeckillEnum;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.LogIntegralMapper;
import com.mdd.common.mapper.OrderUrgeMsgMapper;
import com.mdd.common.mapper.RefundLogMapper;
import com.mdd.common.mapper.RefundRecordMapper;
import com.mdd.common.mapper.ShopMapper;
import com.mdd.common.mapper.VipRecordMapper;
import com.mdd.common.mapper.cart.CartMapper;
import com.mdd.common.mapper.coupon.CouponListMapper;
import com.mdd.common.mapper.coupon.CouponMapper;
import com.mdd.common.mapper.delivery.ExpressCompanyMapper;
import com.mdd.common.mapper.delivery.ExpressTplMapper;
import com.mdd.common.mapper.distribution.DistributionGoodsMapper;
import com.mdd.common.mapper.distribution.DistributionLevelMapper;
import com.mdd.common.mapper.distribution.DistributionMapper;
import com.mdd.common.mapper.distribution.DistributionOrderMapper;
import com.mdd.common.mapper.goods.GoodsMapper;
import com.mdd.common.mapper.goods.GoodsSkuMapper;
import com.mdd.common.mapper.log.LogEarningsMapper;
import com.mdd.common.mapper.log.LogMoneyMapper;
import com.mdd.common.mapper.log.LogOrderAfterMapper;
import com.mdd.common.mapper.log.LogOrderMapper;
import com.mdd.common.mapper.order.OrderAfterGoodsMapper;
import com.mdd.common.mapper.order.OrderAfterMapper;
import com.mdd.common.mapper.order.OrderGoodsMapper;
import com.mdd.common.mapper.order.OrderMapper;
import com.mdd.common.mapper.seckill.SeckillActivityMapper;
import com.mdd.common.mapper.seckill.SeckillGoodsSkuMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.plugin.alipay.AliPayDriver;
import com.mdd.common.plugin.alipay.request.AliPayRefundRequest;
import com.mdd.common.plugin.delivery.DeliveryDriver;
import com.mdd.common.plugin.delivery.vo.KdQueryTrackParam;
import com.mdd.common.plugin.delivery.vo.KdTrackResultVo;
import com.mdd.common.plugin.wechat.WxPayDriver;
import com.mdd.common.plugin.wechat.request.RefundRequestV3;
import com.mdd.common.util.AmountUtil;
import com.mdd.common.util.ConfigUtils;
import com.mdd.common.util.ListUtils;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import com.mdd.common.util.em.EMServiceUtil;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.IOrderService;
import com.mdd.front.service.IUserAddressService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.order.BuyGoodsValidate;
import com.mdd.front.validate.order.OrderAfterCreateValidate;
import com.mdd.front.validate.order.OrderSettleValidate;
import com.mdd.front.vo.goods.GoodsShareVo;
import com.mdd.front.vo.order.OrderDetailVo;
import com.mdd.front.vo.order.OrderGoodsInfoVo;
import com.mdd.front.vo.order.OrderGoodsListVo;
import com.mdd.front.vo.order.OrderListVo;
import com.mdd.front.vo.order.OrderLogisticsVo;
import com.mdd.front.vo.order.OrderSettleResultVo;
import com.mdd.front.vo.order.OrderSubmitResultVo;
import com.mdd.front.vo.user.UserAddressVo;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl implements IOrderService {

	@Resource
	GoodsMapper goodsMapper;

	@Resource
	GoodsSkuMapper goodsSkuMapper;

	@Resource
	OrderMapper orderMapper;

	@Resource
	OrderGoodsMapper orderGoodsMapper;

	@Resource
	OrderAfterMapper orderAfterMapper;

	@Resource
	LogOrderMapper logOrderMapper;

	@Resource
	ExpressTplMapper expressTplMapper;

	@Resource
	CartMapper cartMapper;

	@Resource
	UserMapper userMapper;

	@Resource
	LogOrderAfterMapper logOrderAfterMapper;

	@Resource
	LogMoneyMapper logMoneyMapper;

	@Resource
	RefundRecordMapper refundRecordMapper;

	@Resource
	RefundLogMapper refundLogMapper;

	@Resource
	OrderAfterGoodsMapper orderAfterGoodsMapper;

	@Resource
	ExpressCompanyMapper expressCompanyMapper;

	@Resource
	SeckillActivityMapper seckillActivityMapper;

	@Resource
	SeckillGoodsSkuMapper seckillGoodsSkuMapper;

	@Resource
	CouponMapper couponMapper;

	@Resource
	CouponListMapper couponListMapper;

	@Resource
	DistributionOrderMapper distributionOrderMapper;

	@Resource
	IUserAddressService iUserAddressService;

	@Resource
	DataSourceTransactionManager transactionManager ;

	@Resource
	TransactionDefinition transactionDefinition;

	@Resource
	DistributionGoodsMapper distributionGoodsMapper;

	@Autowired
	private OrderUrgeMsgMapper orderUrgeMsgMapper;

	@Resource
	DistributionMapper distributionMapper;
	@Resource
	DistributionLevelMapper distributionLevelMapper;
	@Resource
	LogIntegralMapper logIntegralMapper;
	@Resource
	VipRecordMapper vipRecordMapper;
	@Resource
	LogEarningsMapper logEarningsMapper;
	@Autowired
	EMServiceUtil eMServiceUtil;
	@Autowired
	ShopMapper shopMapper;

	private BigDecimal hundred = new BigDecimal("100");

	/**
	 * 结算订单
	 *
	 * @author mjf
	 * @param orderSettleValidate OrderSettleValidate
	 * @return OrderSettleResultVo
	 */
	@Override
	public OrderSettleResultVo settlementOrder(OrderSettleValidate orderSettleValidate) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		// 商品信息
		List<OrderGoodsInfoVo> orderGoodsList = getOrderGoodsInfo(userId, orderSettleValidate);
		// 用户地址
		UserAddressVo userAddress = iUserAddressService.getUserAddressById(userId, orderSettleValidate.getAddressId());

		// 订单商品数量
		Integer totalNum = 0;
		// 商品总金额
		BigDecimal goodsAmount = BigDecimal.ZERO;
		for (OrderGoodsInfoVo goodsInfoVo : orderGoodsList) {
			// 商品数量
			totalNum += goodsInfoVo.getNum();
			// 商品金额
			goodsAmount = goodsAmount.add(goodsInfoVo.getGoodsAmount());
		}

		// 秒杀活动ID
		int seckillId = 0;
		// 订单类型
		int orderType = OrderEnum.ORDER_SOURCE_NORMAL.getCode();
		if (orderGoodsList.get(0).getGoodsType().equals(OrderGoodsEnum.GOODS_TYPE_SECKILL.getCode())) {
			orderType = OrderEnum.ORDER_SOURCE_SECKILL.getCode();
			seckillId = orderSettleValidate.getBuyGoods().get(0).getSeckillId();
		}

		//计算优惠券
		//        Integer couponListId = orderSettleValidate.getCouponListId();
		List<Integer> couponListId=new ArrayList<>();
		if(orderSettleValidate.getCouponListId()!=null && orderSettleValidate.getCouponListId().size()>0){
			//可用优惠券集合
			orderSettleValidate.getCouponListId().forEach(item->{
				couponListId.add(item);
			});
		}

		if(orderSettleValidate.getBuyGoods()!=null && orderSettleValidate.getBuyGoods().size()>0){
			//可用优惠券集合
			orderSettleValidate.getBuyGoods().forEach(item->{
				if(item.getCouponListId()!=null && item.getCouponListId().size()>0){
					for (Integer i : item.getCouponListId()) {
						couponListId.add(i);
					}
				}
			});
		}
		BigDecimal couponAmount = BigDecimal.ZERO;
		if (orderType == OrderEnum.ORDER_SOURCE_NORMAL.getCode()) {
			couponAmount = calculateCoupon(orderGoodsList, couponListId, userId);
		}

		// 计算运费
		BigDecimal totalFreight = calculateFreight(orderGoodsList);
		// 订单总金额
		BigDecimal totalAmount = goodsAmount.add(totalFreight);
		// 订单应付金额
		BigDecimal orderAmount = totalAmount.subtract(couponAmount);

		// 配送方式
		String deliveryName = ConfigUtils.getMap("express", "method").getOrDefault("expressName", "快递发货");

		// 订单结算数据
		OrderSettleResultVo settleResultVo = new OrderSettleResultVo();
		settleResultVo.setOrderAmount(orderAmount);
		settleResultVo.setGoodsAmount(goodsAmount);
		settleResultVo.setTotalNum(totalNum);
		settleResultVo.setAddress(userAddress);
		settleResultVo.setFreightAmount(totalFreight);
		settleResultVo.setTotalAmount(totalAmount);
		settleResultVo.setGoods(orderGoodsList);
		settleResultVo.setDeliveryType(1);

		settleResultVo.setDeliveryTypeDesc(deliveryName);
		settleResultVo.setRemark(orderSettleValidate.getRemark());
		settleResultVo.setSeckillId(seckillId);
		settleResultVo.setOrderType(orderType);
		settleResultVo.setCouponAmount(couponAmount);
		settleResultVo.setCouponListId(couponListId);
		settleResultVo.setShareUserId(orderSettleValidate.getShareUserId());
		return settleResultVo;
	}

	/**
	 * 提交订单
	 *
	 * @author mjf
	 * @param orderSettleValidate OrderSettleValidate
	 * @return SubmitOrderResultVo
	 */
	@Override
	public OrderSubmitResultVo submitOrder(OrderSettleValidate orderSettleValidate) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		if(null == orderSettleValidate.getShareUserId()) {
			orderSettleValidate.setShareUserId(0);
		}
		// 购买类型 [buyNow=立即购买 cart=购物车购买]
		String buyType = orderSettleValidate.getBuyType();
		// 计算订单金额
		OrderSettleResultVo settleResultVo = settlementOrder(orderSettleValidate);

		// 订单商品信息
		List<BuyGoodsValidate> buyGoodsValidate = orderSettleValidate.getBuyGoods();
		List<OrderGoodsInfoVo> orderGoodsList = settleResultVo.getGoods();

		// 添加订单，订单日志
		settleResultVo.setToUserId(orderSettleValidate.getToUserId());
		Order order = addOrder(settleResultVo, userId);


		// 购物车下单，清除购物车
		this.__deleteCart(buyType, buyGoodsValidate);
		// 扣除库存
		this.__updateGoodsStock(orderGoodsList);
		// 删除优惠券
		this.__updateCouponList(settleResultVo.getCouponListId(), order.getId(), userId);

		// 返回订单参数
		OrderSubmitResultVo submitResultVo = new OrderSubmitResultVo();
		submitResultVo.setOrderId(order.getId());
		submitResultVo.setOrderSn(order.getOrderSn());
		submitResultVo.setNeedPayMoney(order.getNeedPayMoney());
		return submitResultVo;
	}

	/**
	 * 订单列表
	 *
	 * @author mjf
	 * @param pageValidate PageValidate
	 * @param status Integer
	 * @return PageResult<OrderListVo>
	 */
	@Override
	public PageResult<OrderListVo> list(PageValidate pageValidate, Integer status, Integer toUserId, Integer type) {
		// 分页
		//		Integer userId = 403;//LikeFrontThreadLocal.getUserId();
		Integer userId = LikeFrontThreadLocal.getUserId();
		Integer pageNo = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();
		QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
		// 订单状态 1=待付款, 2=待发货, 3=待收货, 4=待分享, 5=评价
		if (status > 0) {
			if(4 == status || 5 == status) {
				orderQueryWrapper.eq("order_status", 4);
			}else {
				orderQueryWrapper.eq("order_status", status);
			}
			if(5 == status) {
				orderQueryWrapper.eq("is_comment", 0);
			}
		}
		orderQueryWrapper.eq("is_delete", 0);
		orderQueryWrapper.eq("main_order", 1);
		// 0=全部 1=收到 2=送出
		if(-1 == type) {
			orderQueryWrapper.eq("user_id", userId);
		}else if(0 == type){
			orderQueryWrapper.and(i ->i.eq("user_id", userId).or().eq("user_id", toUserId));
			orderQueryWrapper.and(i ->i.eq("to_user_id", userId).or().eq("to_user_id", toUserId));
		}else if(1 == type) {
			orderQueryWrapper.eq("to_user_id", userId).eq("user_id", toUserId);
		}else if(2 == type) {
			orderQueryWrapper.eq("to_user_id", toUserId).eq("user_id", userId);
		}
		orderQueryWrapper.orderByDesc("id");
		IPage<Order> iPage = orderMapper.selectPage(new Page<>(pageNo, pageSize), orderQueryWrapper);
		// 处理数据
		List<OrderListVo> orderList = new ArrayList<>();
		for (Order record : iPage.getRecords()) {
			OrderListVo orderListVo = new OrderListVo();
			BeanUtils.copyProperties(record, orderListVo);
			// 订单商品
			//            List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().
			//                    eq("order_id", record.getId())
			//                    .select("id,goods_id,goods_name,goods_sku_id,goods_sku_value,goods_image,goods_num,goods_price," +
			//                            "goods_original_price,need_pay_money,goods_money"));

			MPJQueryWrapper<OrderGoods> mpjQueryWrapper = new MPJQueryWrapper<OrderGoods>();
			mpjQueryWrapper.eq("order_id", record.getId());
			mpjQueryWrapper .leftJoin("?_goods gs ON  gs.id= t.goods_id".replace("?_", GlobalConfig.tablePrefix));
			mpjQueryWrapper.leftJoin("?_shop sp ON  sp.id= gs.shop_id".replace("?_", GlobalConfig.tablePrefix));
			mpjQueryWrapper.select("t.id,t.goods_id,t.goods_name,t.goods_sku_id,t.goods_sku_value,t.goods_image,t.goods_num,t.goods_price," +
					"t.goods_original_price,t.need_pay_money,t.goods_money,gs.is_cashback,gs.integral_num,gs.express_type,gs.is_reason,gs.is_freight," +
					"sp.name as shop_name,sp.logo as shop_logo,sp.id as shop_id");
			if(4 == status) { // 待分享
				mpjQueryWrapper.innerJoin("?_order o ON o.id = t.order_id".replace("?_", GlobalConfig.tablePrefix));
				//            	mpjQueryWrapper.innerJoin("?_distribution_goods dg ON t.goods_id=dg.goods_id".replace("?_", GlobalConfig.tablePrefix));
				mpjQueryWrapper.eq("o.order_status", OrderEnum.ORDER_STATUS_COMPLETED.getCode());
				//            	mpjQueryWrapper.eq("dg.is_distribution", 1);
			}else if(5 == status) { // 评价
				mpjQueryWrapper.innerJoin("?_order o ON o.id = t.order_id".replace("?_", GlobalConfig.tablePrefix));
				mpjQueryWrapper.eq("o.order_status", OrderEnum.ORDER_STATUS_COMPLETED.getCode());
				//mpjQueryWrapper.eq("t.can_comment", 1);
				mpjQueryWrapper.eq("t.is_comment", 0);
			}

			List<OrderGoods> orderGoodsList = orderGoodsMapper.selectJoinList(OrderGoods.class,mpjQueryWrapper);
			List<OrderGoodsListVo> orderGoodsListVos = new ArrayList<>();
			for (OrderGoods orderGoods : orderGoodsList) {
				orderGoods.setGoodsImage(UrlUtils.toAbsoluteUrl(orderGoods.getGoodsImage()));
				OrderGoodsListVo orderGoodsListVo = new OrderGoodsListVo();
				BeanUtils.copyProperties(orderGoods, orderGoodsListVo);
				orderGoodsListVo.setShopId(orderGoods.getShopId().toString());
				orderGoodsListVos.add(orderGoodsListVo);
			}
			// 订单商品信息
			orderListVo.setOrderGoodsList(orderGoodsListVos);

			// 订单信息
			orderListVo.setOrderStatus(record.getOrderStatus());
			orderListVo.setOrderStatusMsg(OrderEnum.getOrderStatusMsg(record.getOrderStatus()));
			orderListVo.setCancelTime(getCancelUnpaidOrderTime(record.getCreateTime()));
			// 订单按钮
			orderListVo.setPayBtn(__payBtn(record));
			orderListVo.setCancelBtn(__cancelBtn(record));
			orderListVo.setConfirmBtn(__confirmBtn(record));
			orderListVo.setCommentBtn(__commentBtn(record));
			orderListVo.setDeleteBtn(__deleteBtn(record));
			orderListVo.setRefundBtn(__refundBtn(record));
			orderListVo.setLogisticsBtn(__logisticsBtn(record));
			orderListVo.setUrgeBtn(__urgeBtn(record));
			orderListVo.setShareBtn(__shareBtn(record));
			orderListVo.setAfterSalesBtn(__afterSalesBtn(record));
			if(CollectionUtil.isNotEmpty(orderGoodsListVos)) {
				orderListVo.setShopId(orderGoodsListVos.get(0).getShopId());
			}
			orderList.add(orderListVo);
		}
		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), orderList);
	}

	public static void main(String[] args) {
		List<OrderGoodsListVo> orderGoodsListVos = new ArrayList<>();
		System.out.println(orderGoodsListVos.get(0).getShopId());
	}
	/**
	 * 订单详情
	 *
	 * @author mjf
	 * @param id Integer
	 * @return OrderDetailVo
	 */
	@Override
	public OrderDetailVo detail(Integer id) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		// 订单
		Order order = orderMapper.selectOne(new QueryWrapper<Order>()
				.eq("id", id)
				.eq("user_id", userId)
				.eq("is_delete", 0)
				.last("limit 1"));

		Assert.notNull(order, "订单信息不存在");

		// 订单商品
		List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>()
				.eq("order_id",order.getId()));

		// 订单商品处理
		List<OrderGoodsListVo> orderGoodsListVoList = new ArrayList<>();
		for (OrderGoods orderGoods : orderGoodsList) {
			OrderGoodsListVo orderGoodsListVo = new OrderGoodsListVo();
			BeanUtils.copyProperties(orderGoods, orderGoodsListVo);
			orderGoodsListVo.setGoodsImage(UrlUtils.toAbsoluteUrl(orderGoods.getGoodsImage()));
			orderGoodsListVo.setAfterSalesBtn(this.__afterApplyBtn(order, orderGoods.getId()));
			orderGoodsListVo.setAfterSalesMsg(this.__afterApplyMsg(order,orderGoods.getId()));
			orderGoodsListVo.setShopId(orderGoods.getShopId().toString());
			orderGoodsListVoList.add(orderGoodsListVo);
		}

		// 订单信息处理
		OrderDetailVo orderDetailVo = new OrderDetailVo();
		BeanUtils.copyProperties(order, orderDetailVo);
		orderDetailVo.setOrderTypeMsg(OrderEnum.getOrderTypeMsg(order.getOrderType()));
		orderDetailVo.setOrderGoodsList(orderGoodsListVoList);
		orderDetailVo.setCreateTime(TimeUtils.timestampToDate(order.getCreateTime()));

		String expressTime = order.getExpressTime() > 0 ? TimeUtils.timestampToDate(order.getExpressTime()) : "-";
		String payTime = order.getPayTime() > 0 ? TimeUtils.timestampToDate(order.getPayTime()) : "-";
		String confirmTime = order.getConfirmTime() > 0 ? TimeUtils.timestampToDate(order.getConfirmTime()) : "-";
		orderDetailVo.setExpressTime(expressTime);
		orderDetailVo.setPayTime(payTime);
		orderDetailVo.setConfirmTime(confirmTime);
		orderDetailVo.setCancelTime(getCancelUnpaidOrderTime(order.getCreateTime()));
		orderDetailVo.setOrderStatus(order.getOrderStatus());
		orderDetailVo.setOrderStatusMsg(OrderEnum.getOrderStatusMsg(order.getOrderStatus()));
		orderDetailVo.setShopId(orderGoodsListVoList.get(0).getShopId());
		// 订单按钮
		orderDetailVo.setPayBtn(__payBtn(order));
		orderDetailVo.setCancelBtn(__cancelBtn(order));
		orderDetailVo.setConfirmBtn(__confirmBtn(order));
		orderDetailVo.setDeleteBtn(__deleteBtn(order));
		orderDetailVo.setCommentBtn(__commentBtn(order));
		orderDetailVo.setLogisticsBtn(__logisticsBtn(order));
		orderDetailVo.setRefundBtn(__refundBtn(order));
		return orderDetailVo;
	}

	/**
	 * 待分享
	 *@param pageValidate
	 */
	@Override
	public PageResult<GoodsShareVo> share(PageValidate pageValidate,String name) {
		// 分页
		Integer userId = LikeFrontThreadLocal.getUserId();
		Integer pageNo = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();

		//判断用户是否是分销商（1、分销商能分销所有加入分销的商品 2、普通能分享所有商品但是只能获取到积分）
		//        Long userCount = userMapper.selectCount(new MPJQueryWrapper<User>()
		//                        .select("t.id")
		//                        .innerJoin("?_distribution D ON D.user_id = t.id".replace("?_", GlobalConfig.tablePrefix))
		//                        .eq("D.is_distribution", 1)
		//                        .eq("D.is_freeze", 0)
		//                        .eq("t.is_delete", 0)
		//                        .eq("t.is_close", 0)
		//                        .eq("t.id", userId));


		// 处理数据
		//        List<GoodsShareVo> goodsListVos = new ArrayList<>();
		List<GoodsShareVo> goodsListVos1 = new ArrayList<>();

		//        if(userCount<=0){//普通用户
		//查出确认收货后购买商品的id
		//            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
		//            orderQueryWrapper.eq("is_delete", 0)
		//                    .eq("order_status",OrderEnum.ORDER_STATUS_COMPLETED.getCode())
		//                    .eq("user_id", userId)
		//                    .orderByDesc("id");
		//            IPage<Order> iPage = orderMapper.selectPage(new Page<>(pageNo, pageSize), orderQueryWrapper);
		//
		//            for (Order record : iPage.getRecords()) {
		//                OrderListVo orderListVo = new OrderListVo();
		//                BeanUtils.copyProperties(record, orderListVo);
		//                // 订单商品
		//                List<GoodsShareVo> orderGoodsList = orderGoodsMapper.selectJoinList(
		//                        GoodsShareVo.class,
		//                        new MPJQueryWrapper<OrderGoods>()
		//                                .eq("order_id", record.getId())
		//                                .leftJoin("?_goods gs ON  gs.id= t.goods_id".replace("?_", GlobalConfig.tablePrefix))
		//                                .leftJoin("?_shop sp ON  sp.id= gs.shop_id".replace("?_", GlobalConfig.tablePrefix))
		//                                .innerJoin("?_distribution_goods dg ON dg.goods_id=t.goods_id".replace("?_", GlobalConfig.tablePrefix))
		//                                .eq("dg.is_distribution",1)
		//                                .eq("dg.is_delete",0)
		//                                .select("sp.id AS shop_id,sp.`name` AS shop_name,gs.`name` AS goods_name,gs.id AS goods_id,gs.express_type," +
		//                                        "gs.is_freight,gs.min_price,gs.integral_num,gs.image AS goods_image"));
		//
		//                for (GoodsShareVo orderGoods : orderGoodsList) {
		//                    orderGoods.setGoodsImage(UrlUtils.toAbsoluteUrl(orderGoods.getGoodsImage()));
		//                    GoodsShareVo orderGoodsListVo = new GoodsShareVo();
		//                    BeanUtils.copyProperties(orderGoods, orderGoodsListVo);
		//                    goodsListVos.add(orderGoodsListVo);
		//                }
		//            }
		//            return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), goodsListVos);
		//        }else {//分销商
		//查询所有分销商品
		//            QueryWrapper<DistributionGoods> distributionGoodsWrapper = new QueryWrapper<>();
		//            distributionGoodsWrapper.eq("is_distribution", 1)
		//                    .eq("is_delete", 0);
		//            IPage<DistributionGoods> iPage = distributionGoodsMapper.selectPage(new Page<>(pageNo, pageSize), distributionGoodsWrapper);
		//            for (DistributionGoods record : iPage.getRecords()){
		MPJQueryWrapper<Goods> select = new MPJQueryWrapper<Goods>();
		//            			select.eq("t.id",record.getGoodsId());
		select.eq("t.`status`",1);
		select.leftJoin("?_shop sp ON sp.id = t.shop_id".replace("?_", GlobalConfig.tablePrefix));
		select.leftJoin("?_distribution_goods dg ON dg.goods_id = t.id".replace("?_", GlobalConfig.tablePrefix));
		select.select("sp.id AS shop_id,sp.`name` AS shop_name,t.`name` AS goods_name,t.id AS goods_id," +
				"t.express_type,t.is_freight,t.min_price,t.integral_num,t.image AS goods_image");
		if(StringUtils.isNotEmpty(name)) {
			select.like("t.name", name);
		}
		select.eq("dg.is_distribution", 1);
		select.eq("dg.is_delete", 0);
		IPage<GoodsShareVo> iPage = goodsMapper.selectJoinPage(new Page<>(pageNo, pageSize),
				GoodsShareVo.class,select);
		for (GoodsShareVo goods : iPage.getRecords()) {
			goods.setGoodsImage(UrlUtils.toAbsoluteUrl(goods.getGoodsImage()));
			GoodsShareVo orderGoodsListVo = new GoodsShareVo();
			BeanUtils.copyProperties(goods, orderGoodsListVo);
			goodsListVos1.add(orderGoodsListVo);
		}
		//            }
		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), goodsListVos1);
		//        }

	}

	/**
	 * 	下单返现
	 * @param goods
	 * @param userId
	 * @param orderSn
	 */
	private void cashback(Goods goods,Integer userId,Order order,BigDecimal price) {
		// 修改用户积分(金币)
		BigDecimal coin = BigDecimal.ZERO;
		if(null != goods.getCashbackRatio() && goods.getCashbackRatio().compareTo(BigDecimal.ZERO) > 0) {
			BigDecimal ratio = goods.getCashbackRatio().divide(hundred,2, RoundingMode.HALF_UP);
			coin = price.multiply(ratio).setScale(2, RoundingMode.HALF_UP);
		}
		if(coin.compareTo(BigDecimal.ZERO) > 0) {
			userMapper.update(null, new UpdateWrapper<User>()
					.eq("id", userId)
					.setSql("integral = integral+"+coin.multiply(hundred)));
			logIntegralMapper.add(
					userId, LogMoneyEnum.UI_INC_GOODS.getCode(), coin.multiply(hundred), goods.getId(), order.getOrderSn(),
					"购物返金币", "");
			eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(userId), "本次获得金币"+coin.multiply(hundred));
		}
	}
	
	private BigDecimal cashbackAdd(OrderGoodsInfoVo goods,BigDecimal price) {
		// 修改用户积分(金币)
		BigDecimal coin = BigDecimal.ZERO;
		if(null != goods.getCashbackRatio() && goods.getCashbackRatio().compareTo(BigDecimal.ZERO) > 0) {
			BigDecimal ratio = goods.getCashbackRatio().divide(hundred,2, RoundingMode.HALF_UP);
			coin = price.multiply(ratio).setScale(2, RoundingMode.HALF_UP);
		}
		if(coin.compareTo(BigDecimal.ZERO) > 0) {
			coin = coin.multiply(hundred);
		}
		
		return coin;
	}


	/**
	 * 确认收货
	 *
	 * @author mjf
	 * @param id Integer
	 */
	@Override
	public void confirm(Integer id) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		// 订单
		Order order = orderMapper.selectOne(new QueryWrapper<Order>()
				.eq("id", id)
				.eq("user_id", userId)
				.eq("is_delete", 0)
				.last("limit 1"));

		Assert.notNull(order, "订单信息不存在");
		if (order.getOrderStatus() <= OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode()) {
			throw new OperateException("订单未发货");
		}
		if (order.getOrderStatus() >= OrderEnum.ORDER_STATUS_COMPLETED.getCode()) {
			throw new OperateException("订单已完成");
		}

		// 更新信息
		order.setOrderStatus(OrderEnum.ORDER_STATUS_COMPLETED.getCode());
		order.setConfirmTime(System.currentTimeMillis() / 1000);
		// 售后截止时间
		order.setAfterDeadline(__getAfterSaleDeadline());
		orderMapper.updateById(order);
		// 订单日志
		logOrderMapper.add(order.getId(),
				OrderLogEnum.TYPE_USER.getCode(),
				OrderLogEnum.CHANNEL_USER_CONFIRM_ORDER.getCode(),
				userId,OrderLogEnum.CHANNEL_USER_CONFIRM_ORDER.getMsg());

		BigDecimal marketPrice = BigDecimal.ZERO;
		List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId, id));
		if(order.getPayWay() != 4) {
			User user = userMapper.selectById(order.getUserId());
			Integer userLevelCurr = 1;
			// 查询用户VIP等级
			Distribution distributionCurr = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, userId));
			if(null != distributionCurr && null != distributionCurr.getExpireTime() && distributionCurr.getExpireTime() > TimeUtils.timestamp()) {
				userLevelCurr = distributionCurr.getLevelId();
			}
			// 确认收货检验是否有分享者
			for (OrderGoods orderGoods : orderGoodsList) {
				// 查询产品分佣类型
				Goods goods = goodsMapper.selectOne(new LambdaQueryWrapper<Goods>().eq(Goods::getId, orderGoods.getGoodsId()).ne(Goods::getCommissionType, 3));
				if(null == goods) {
					continue;
				}
				// 获取购买的规格
				GoodsSku goodsSku = goodsSkuMapper.selectById(orderGoods.getGoodsSkuId());
				if(null == goodsSku) {
					continue;
				}
				marketPrice = marketPrice.add(goodsSku.getMarketPrice());
				BigDecimal couponAmount = BigDecimal.ZERO;
				// 领券优惠金额
				if(StringUtils.isNotEmpty(order.getCouponListId())) {
					if(!"0".equals(order.getCouponListId())){
						BigDecimal _m1 = order.getNeedPayMoney().subtract(order.getExpressMoney());
						BigDecimal _m2 = _m1.divide(order.getGoodsMoney(),2, RoundingMode.HALF_UP);
						BigDecimal _m3 = _m2.multiply(orderGoods.getMoney());
						couponAmount = orderGoods.getMoney().subtract(_m3);
					}
				}
				BigDecimal price = BigDecimal.ZERO;
				// 计算产品类型且分佣金额
				if(null != goods.getCashbackRatio() && goods.getCashbackRatio().compareTo(BigDecimal.ZERO) > 0) {
					if(goods.getCommissionType() == 1) {	// 利润 【产品售价-产品供货价-领券优惠金额】
						price = goodsSku.getPrice().subtract(goodsSku.getMarketPrice()).subtract(couponAmount);

					}else {	// 差价 【产品售价*百分比（如5%）-领券优惠金额】
						BigDecimal divide = goods.getCommissionRatio().divide(hundred,2, RoundingMode.HALF_UP);
						BigDecimal multiply = goodsSku.getPrice().multiply(divide);
						price = multiply.subtract(couponAmount);
					}
				}
				price = price.multiply(new BigDecimal(orderGoods.getGoodsNum()));
				// 下单再返
				cashback(goods, orderGoods.getUserId(), order,price);
				// 分享分佣
				if(price.compareTo(BigDecimal.ZERO) > 0 && orderGoods.getShareUserId() > 0) {
					Distribution distribution = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, orderGoods.getShareUserId()));
					if(null != distribution) {
						Integer userLevel = distribution.getLevelId();
						if(distribution.getExpireTime() < TimeUtils.timestamp()) {
							userLevel = 1;
						}
						BigDecimal cashbackAmount = BigDecimal.ZERO;
						// 计算等级分佣
						if(2 == userLevel) {
							BigDecimal divide = goods.getLevel1Silver().divide(hundred,2,RoundingMode.HALF_UP);
							cashbackAmount = price.multiply(divide);
						}else if(3 == userLevel) {
							BigDecimal divide = goods.getLevel1Gold().divide(hundred,2,RoundingMode.HALF_UP);
							cashbackAmount = price.multiply(divide);
						}else if(4 == userLevel) {
							BigDecimal divide = goods.getLevel1Diamond().divide(hundred,2,RoundingMode.HALF_UP);
							cashbackAmount = price.multiply(divide);
						}
						if(cashbackAmount.compareTo(BigDecimal.ZERO) > 0) {
							if(userLevel >= 4) {
								userMapper.update(null, new UpdateWrapper<User>()
										.eq("id", orderGoods.getShareUserId())
										.setSql("earnings = earnings+"+ cashbackAmount));
								logEarningsMapper.add(
										orderGoods.getShareUserId(), LogMoneyEnum.UE_INC_GOODS.getCode(), cashbackAmount, goods.getId(), order.getOrderSn(), "分享产品增加余额", "");
								eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(orderGoods.getShareUserId()), "本次获得余额"+cashbackAmount);

							}else {
								userMapper.update(null, new UpdateWrapper<User>()
										.eq("id", orderGoods.getShareUserId())
										.setSql("integral = integral+"+(cashbackAmount.multiply(hundred))));
								logIntegralMapper.add(
										orderGoods.getShareUserId(), LogMoneyEnum.UI_INC_SHARE.getCode(), cashbackAmount.multiply(hundred), goods.getId(), order.getOrderSn(), "分享产品增加金币", "");

								eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(orderGoods.getShareUserId()), "本次获得金币"+cashbackAmount.multiply(hundred));
							}
						}
					}
				}
				// 是否是分佣产品
				__handleCommission(goods, orderGoods.getUserId(), order,price,userLevelCurr,user);
			}
			//下单判断是否需要升级vip
			this.receiveVip(userId,order,orderGoodsList);
		}
		for (OrderGoods orderGoods : orderGoodsList) {
			// 获取购买的规格
			GoodsSku goodsSku = goodsSkuMapper.selectById(orderGoods.getGoodsSkuId());
			if(null == goodsSku) {
				continue;
			}
			BigDecimal multiply = goodsSku.getMarketPrice().multiply(BigDecimal.valueOf(orderGoods.getGoodsNum()));
			marketPrice = marketPrice.add(multiply);
		}
		// 增加商户余额
		Shop shop = shopMapper.selectById(order.getShopId());
		if(null != shop && marketPrice.compareTo(BigDecimal.ZERO) > 0) {
			shop.setTotalAmount(shop.getTotalAmount().add(marketPrice));
			shopMapper.updateById(shop);
		}
	}

	/**
	 * 	计算产品分佣 2024-11-27
	 */

	public void __handleCommission(Goods goods,Integer userId,Order order,BigDecimal price,Integer userLevel,User user) {
		if(price.compareTo(BigDecimal.ZERO) > 0) {
			if(user.getFirstLeader() <= 0) {
				return;
			}
			Distribution distributionFirst = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, user.getFirstLeader()));
			if(distributionFirst == null) {
				return;
			}else if(distributionFirst.getLevelId() <= 1 || distributionFirst.getExpireTime() < TimeUtils.timestamp()){
				return;
			}
			DistributionLevel distributionLevelFirst = distributionLevelMapper.selectById(distributionFirst.getLevelId());

			DistributionLevel distributionLevelSecond = null;
			Distribution distributionSecond = null;
			if(user.getSecondLeader() > 0) {
				distributionSecond = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, user.getSecondLeader()));
				if(null != distributionSecond && distributionSecond.getLevelId() > 1 && distributionSecond.getExpireTime() > TimeUtils.timestamp()) {
					distributionLevelSecond = distributionLevelMapper.selectById(distributionSecond.getLevelId());
				}
			}
			//  所有用户利润1%现金 / 2%
			if(null != distributionLevelFirst.getFirstRatio() && BigDecimal.valueOf(distributionLevelFirst.getFirstRatio()).compareTo(BigDecimal.ZERO) > 0) {
				BigDecimal _ratio = BigDecimal.valueOf(distributionLevelFirst.getFirstRatio()).divide(hundred);
				if(distributionFirst.getLevelId() == 6 || distributionFirst.getLevelId() == 7) {
					BigDecimal _earnings = price.multiply(_ratio);
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getFirstLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getFirstLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "团队用户利润", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得余额"+_earnings);
				}
			}
			// 上上级团队利润
			if(null != distributionLevelSecond.getFirstRatio() && BigDecimal.valueOf(distributionLevelSecond.getFirstRatio()).compareTo(BigDecimal.ZERO) > 0) {
				BigDecimal _ratio = BigDecimal.valueOf(distributionLevelSecond.getFirstRatio()).divide(new BigDecimal("100"));
				if(distributionSecond.getLevelId() == 6 || distributionSecond.getLevelId() == 7) {
					BigDecimal _earnings = price.multiply(_ratio);
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "团队用户利润", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得余额"+_earnings);
				}
			}
			// 上级
			if(distributionFirst.getLevelId() >= 4) { // 钻石以上是余额
				BigDecimal ratio = goods.getLevel1Diamond().divide(hundred,2, RoundingMode.HALF_UP);
				BigDecimal _earnings = price.multiply(ratio);
				userMapper.update(null, new UpdateWrapper<User>()
						.eq("id", user.getFirstLeader())
						.setSql("earnings = earnings+"+_earnings));
				logEarningsMapper.add(
						user.getFirstLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "上级代理余额", "");
				eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得余额"+_earnings);
			}else {	// 钻石以下是金币
				BigDecimal _earnings = BigDecimal.ZERO;
				if(distributionFirst.getLevelId() == 2) {
					BigDecimal ratio = goods.getLevel1Silver().divide(hundred,2, RoundingMode.HALF_UP);
					_earnings = price.multiply(ratio);

				}else if(distributionFirst.getLevelId() == 3) {
					BigDecimal ratio = goods.getLevel1Gold().divide(hundred,2, RoundingMode.HALF_UP);
					_earnings = price.multiply(ratio);
				}
				if(distributionFirst.getLevelId() == 2 || distributionFirst.getLevelId() == 3) {
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getFirstLeader())
							.setSql("integral = integral+"+ (_earnings.multiply(hundred))));
					logIntegralMapper.add(
							user.getFirstLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _earnings.multiply(hundred), goods.getId(), order.getOrderSn(), "上级代理金币", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得金币"+_earnings.multiply(hundred));
				}
			}

			// 上上级
			if(null != distributionSecond) {
				if(distributionSecond.getLevelId() >= 4) {
					BigDecimal ratio = goods.getLevel2Diamond().divide(hundred,2, RoundingMode.HALF_UP);
					BigDecimal _ratio = goods.getLevel2DiamondGold().divide(hundred,2, RoundingMode.HALF_UP);
					BigDecimal _earnings = price.multiply(ratio);
					BigDecimal _integral = price.multiply(_ratio);
					
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "上上级代理余额", "");

					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("integral = integral+"+ _integral.multiply(hundred)));
					logIntegralMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _integral.multiply(hundred), goods.getId(), order.getOrderSn(), "上上级代理金币", "");

					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得余额"+_earnings+",金币"+_integral.multiply(hundred));
				}else {
					BigDecimal _earnings = BigDecimal.ZERO;
					if(distributionSecond.getLevelId() == 2) {
						BigDecimal ratio = goods.getLevel2Silver().divide(hundred,2, RoundingMode.HALF_UP);
						_earnings = price.multiply(ratio);
					}else if(distributionSecond.getLevelId() == 3) {
						BigDecimal ratio = goods.getLevel2Gold().divide(hundred,2, RoundingMode.HALF_UP);
						_earnings = price.multiply(ratio);
					}
					if(distributionSecond.getLevelId() == 2 || distributionSecond.getLevelId() == 3) {
						userMapper.update(null, new UpdateWrapper<User>()
								.eq("id", user.getSecondLeader())
								.setSql("integral = integral+"+ (_earnings.multiply(hundred))));
						logIntegralMapper.add(
								user.getSecondLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _earnings.multiply(hundred), goods.getId(), order.getOrderSn(), "上上级代理金币", "");
						eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得金币"+_earnings.multiply(hundred));
					}
				}
			}
		}
	}
	/**
	 * 	计算产品分佣
	 * @param
	 * @param userId
	 */
	private void handleCommission(List<Integer> goodsIds,Integer userId,Order order,User user) {
		List<Goods> goodsList = goodsMapper.selectList(new LambdaQueryWrapper<Goods>().in(Goods::getId, goodsIds));
		if(CollectionUtil.isNotEmpty(goodsList)) {
			Integer userLevel = 1;
			// 修改用户VIP等级
			Distribution distribution = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, userId));
			if(null != distribution && null != distribution.getExpireTime() && distribution.getExpireTime() > TimeUtils.timestamp()) {
				userLevel = distribution.getLevelId();
			}
			for (Goods goods : goodsList) {
				if(goods.getCommissionType() != 3) {
					// 分佣
					superiorCommission(userId, userLevel, goods, order,user);
				}
			}
		}
	}

	/**
	 * 	上级抽佣
	 * @param userId		用户ID
	 * @param userLevel		用户等级
	 * @param goods			商品信息
	 * @param couponListId	优惠总金额
	 * @param user			用户信息
	 */
	public void superiorCommission(Integer userId,Integer userLevel,Goods goods,Order order,User user) {
		if(user.getFirstLeader() <= 0) {
			return;
		}
		Distribution distributionFirst = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, user.getFirstLeader()));
		if(distributionFirst == null) {
			return;
		}else if(distributionFirst.getLevelId() <= 1 || distributionFirst.getExpireTime() < TimeUtils.timestamp()){
			return;
		}
		DistributionLevel distributionLevelFirst = distributionLevelMapper.selectById(distributionFirst.getLevelId());

		DistributionLevel distributionLevelSecond = null;
		Distribution distributionSecond = null;
		if(user.getSecondLeader() > 0) {
			distributionSecond = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, user.getSecondLeader()));
			if(null != distributionSecond && distributionSecond.getLevelId() > 1 && distributionSecond.getExpireTime() > TimeUtils.timestamp()) {
				distributionLevelSecond = distributionLevelMapper.selectById(distributionSecond.getLevelId());
			}
		}
		BigDecimal couponAmount = BigDecimal.ZERO;
		if(null == goods || null == goods.getId()) {
			throw new OperateException("产品有误");
		}
		OrderGoods orderGoods = orderGoodsMapper.selectOne(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId,order.getId()).eq(OrderGoods::getGoodsId, goods.getId())
				.select(OrderGoods::getGoodsPrice));
		if(null == orderGoods || null == orderGoods.getGoodsPrice()) {
			throw new OperateException("产品有误");
		}
		if(StringUtils.isNotEmpty(order.getCouponListId())) {
			if(!"0".equals(order.getCouponListId())){
				BigDecimal _m1 = order.getNeedPayMoney().subtract(order.getExpressMoney());
				BigDecimal _m2 = _m1.divide(order.getGoodsMoney(),2, RoundingMode.HALF_UP);
				BigDecimal _m3 = _m2.multiply(orderGoods.getGoodsPrice());
				couponAmount = orderGoods.getGoodsPrice().subtract(_m3);
			}
		}
		BigDecimal cashbackAmount = BigDecimal.ZERO;
		if(1 == userLevel) {
			cashbackAmount = goods.getCashbackOrdinary();
		}else if(2 == userLevel) {
			cashbackAmount = goods.getCashbackSilver();
		}else if(3 == userLevel) {
			cashbackAmount = goods.getCashbackGold();
		}else if(4 == userLevel) {
			cashbackAmount = goods.getCashbackDiamond();
		}else if(5 == userLevel) {
			cashbackAmount = goods.getCashbackPartner();
		}else if(6 == userLevel) {
			cashbackAmount = goods.getCashbackCreate8();
		}else if(7 == userLevel) {
			cashbackAmount = goods.getCashbackCreate9();
		}
		BigDecimal _c = BigDecimal.ZERO;
		switch (goods.getCommissionType()) {
		case 1:
			// 按利润分佣产品 ： 产品售价-产品供货价-下单再返-领券优惠金额
			_c = orderGoods.getGoodsPrice().subtract(goods.getSupplyPrice()).subtract(cashbackAmount).subtract(couponAmount);
			break;
		case 2:
			// 按售价分佣产品 ： 产品售价-下单再返-领券优惠金额
			_c = orderGoods.getGoodsPrice().subtract(cashbackAmount).subtract(couponAmount);
			break;
		case 3:
			// TODO 月分佣 待沟通
			break;
		}
		if(_c.compareTo(BigDecimal.ZERO) > 0) {
			// 团队会员年费*80%现金 + 所有用户利润1%现金 / 2%
			if(null != distributionLevelFirst.getFirstRatio() && BigDecimal.valueOf(distributionLevelFirst.getFirstRatio()).compareTo(BigDecimal.ZERO) > 0) {
				BigDecimal _ratio = BigDecimal.valueOf(distributionLevelFirst.getFirstRatio()).divide(new BigDecimal("100"));
				if(distributionFirst.getLevelId() == 6 || distributionFirst.getLevelId() == 7) {
					BigDecimal _earnings = _c.multiply(_ratio);
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getFirstLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getFirstLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "团队用户利润", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得余额"+_earnings);
				}
			}
			// 上上级团队利润
			if(null != distributionLevelSecond.getFirstRatio() && BigDecimal.valueOf(distributionLevelSecond.getFirstRatio()).compareTo(BigDecimal.ZERO) > 0) {
				BigDecimal _ratio = BigDecimal.valueOf(distributionLevelSecond.getFirstRatio()).divide(new BigDecimal("100"));
				if(distributionSecond.getLevelId() == 6 || distributionSecond.getLevelId() == 7) {
					BigDecimal _earnings = _c.multiply(_ratio);
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "团队用户利润", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得余额"+_earnings);
				}
			}
			// 上级 上上级抽佣
			if(distributionFirst.getLevelId() >= 4) { // 钻石以上是余额
				BigDecimal _earnings = BigDecimal.ZERO;
				switch (distributionFirst.getLevelId()) {
				case 4:
					_earnings = goods.getLevel1Diamond();
					break;
				case 5:
					_earnings = goods.getLevel1Partner();
					break;
				case 6:
					_earnings = goods.getLevel1Create8();
					break;
				case 7:
					_earnings = goods.getLevel1Create9();
					break;
				}
				userMapper.update(null, new UpdateWrapper<User>()
						.eq("id", user.getFirstLeader())
						.setSql("earnings = earnings+"+_earnings));
				logEarningsMapper.add(
						user.getFirstLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "上级代理余额", "");
				eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得余额"+_earnings);
			}else {	// 钻石以下是金币
				BigDecimal _earnings = BigDecimal.ZERO;
				if(distributionFirst.getLevelId() == 2) {
					_earnings = goods.getLevel1Silver();
				}else if(distributionFirst.getLevelId() == 3) {
					_earnings = goods.getLevel1Gold();
				}
				if(distributionFirst.getLevelId() == 2 || distributionFirst.getLevelId() == 3) {
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getFirstLeader())
							//.setSql("earnings = earnings+"+_earnings));
							.setSql("integral = integral+"+ (_earnings.multiply(hundred))));
					logIntegralMapper.add(
							user.getFirstLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _earnings.multiply(hundred), goods.getId(), order.getOrderSn(), "上级代理金币", "");
					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getFirstLeader()), "本次获得金币"+_earnings.multiply(hundred));
				}
			}
			// 上上级
			if(null != distributionSecond) {
				if(distributionSecond.getLevelId() >= 4) {
					BigDecimal _earnings = BigDecimal.ZERO;
					BigDecimal _integral = BigDecimal.ZERO;
					switch (distributionSecond.getLevelId()) {
					case 4:
						_earnings = goods.getLevel2Diamond();
						_integral = goods.getLevel2DiamondGold();
						break;
					case 5:
						_earnings = goods.getLevel2Partner();
						_integral = goods.getLevel2PartnerGold();
						break;
					case 6:
						_earnings = goods.getLevel2Create8();
						_integral = goods.getLevel2Create8Gold();
						break;
					case 7:
						_earnings = goods.getLevel2Create9();
						_integral = goods.getLevel2Create9Gold();
						break;
					}
					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("earnings = earnings+"+_earnings));
					logEarningsMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UE_INC_GOODS.getCode(), _earnings, goods.getId(), order.getOrderSn(), "上上级代理余额", "");

					userMapper.update(null, new UpdateWrapper<User>()
							.eq("id", user.getSecondLeader())
							.setSql("integral = integral+"+ _integral));
					logIntegralMapper.add(
							user.getSecondLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _integral, goods.getId(), order.getOrderSn(), "上上级代理金币", "");

					eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得余额"+_earnings+",金币"+_integral);
				}else {
					BigDecimal _earnings = BigDecimal.ZERO;
					if(distributionSecond.getLevelId() == 2) {
						_earnings = goods.getLevel2Silver();
					}else if(distributionSecond.getLevelId() == 3) {
						_earnings = goods.getLevel2Gold();
					}
					if(distributionSecond.getLevelId() == 2 || distributionSecond.getLevelId() == 3) {
						userMapper.update(null, new UpdateWrapper<User>()
								.eq("id", user.getSecondLeader())
								.setSql("integral = integral+"+ (_earnings.multiply(hundred))));
						logIntegralMapper.add(
								user.getSecondLeader(), LogMoneyEnum.UI_INC_GOODS.getCode(), _earnings.multiply(hundred), goods.getId(), order.getOrderSn(), "上上级代理金币", "");
						eMServiceUtil.sendNoticeOfReceipt(userMapper.getEmUserName(user.getSecondLeader()), "本次获得金币"+_earnings.multiply(hundred));
					}
				}
			}
		}
	}

	/**
	 * 删除订单
	 *
	 * @author mjf
	 * @param id Integer
	 */
	@Override
	public void del(Integer id) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		// 订单
		Order order = orderMapper.selectOne(new QueryWrapper<Order>()
				.eq("id", id)
				.eq("user_id", userId)
				.eq("is_delete", 0)
				.last("limit 1"));

		Assert.notNull(order, "订单信息不存在");
		if (order.getOrderStatus() != OrderEnum.ORDER_STATUS_CANCEL.getCode() && order.getOrderStatus() != OrderEnum.ORDER_STATUS_COMPLETED.getCode()) {
			throw new OperateException("订单无法删除");
		}

		// 在售后中则无法删除
		OrderAfter orderAfter = orderAfterMapper.selectOne(new QueryWrapper<OrderAfter>()
				.eq("order_id", order.getId())
				.eq("after_status", OrderAfterEnum.AFTER_STATUS_ING.getCode())
				.last("limit 1"));
		if(orderAfter!=null){
			throw new OperateException("订单处于售后中，不可删除");
		}
		order.setIsDelete(1);
		order.setUpdateTime(System.currentTimeMillis() / 1000);
		orderMapper.updateById(order);

		// 订单日志
		logOrderMapper.add(order.getId(),
				OrderLogEnum.TYPE_USER.getCode(),
				OrderLogEnum.CHANNEL_USER_DEL_ORDER.getCode(),
				userId,OrderLogEnum.CHANNEL_USER_DEL_ORDER.getMsg());
	}

	/**
	 * 取消订单
	 *
	 * @author mjf
	 * @param id Integer
	 */
	@Override
	public void cancel(Integer id) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		// 订单
		Order order = orderMapper.selectOne(new QueryWrapper<Order>()
				.eq("id", id)
				.eq("user_id", userId)
				.eq("is_delete", 0)
				.last("limit 1"));

		Assert.notNull(order, "订单信息不存在");
		// 订单已取消
		if (order.getOrderStatus() == OrderEnum.ORDER_STATUS_CANCEL.getCode()) {
			throw new OperateException("订单不可取消");
		}
		// 订单已发货
		/*if (order.getOrderStatus() > OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode()) {
			throw new OperateException("订单不可取消");
		}*/
		// 订单待发货待收货时可取消
		if(order.getOrderStatus() == OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode() || order.getOrderStatus() == OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode()) {
			// 订单允许取消时长
			//            float cancelUnshippedOrderTime = Float.parseFloat(ConfigUtils.get("trade", "cancelUnshippedOrderTime", "-1"));
			//            if (cancelUnshippedOrderTime == -1) {
			//                throw new OperateException("订单不可取消");
			//            }
			//            long ableCancelTime = (long)(cancelUnshippedOrderTime * 60) + order.getPayTime();
			//            if (TimeUtils.timestamp() > ableCancelTime) {
			//                throw new OperateException("订单不可取消");
			//            }
			// 校验是否已产生售后记录
			OrderAfter orderAfter = orderAfterMapper.selectOne(new QueryWrapper<OrderAfter>()
					.eq("order_id", order.getId())
					.in("after_status", Arrays.asList(OrderAfterEnum.AFTER_STATUS_ING.getCode(), OrderAfterEnum.AFTER_STATUS_SUCCESS.getCode()))
					.last("limit 1"));
			if (orderAfter != null) {
				throw new OperateException("订单已发生售后，不可取消");
			}
		}
		// 修改发货通知状态
		LambdaUpdateWrapper<OrderUrgeMsg> updateWrapper = new LambdaUpdateWrapper<OrderUrgeMsg>();
		updateWrapper.eq(OrderUrgeMsg::getOrderId, id);
		OrderUrgeMsg urge = new OrderUrgeMsg();
		urge.setOrderStatus(2);
		urge.setUpdateTime(TimeUtils.timestamp());
		orderUrgeMsgMapper.update(urge, updateWrapper);
		// 取消订单
		this.__handleCancelOrder(order);
	}

	@Override
	public void urge(Integer id) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		// 订单
		Order order = orderMapper.selectOne(new QueryWrapper<Order>()
				.eq("id", id)
				.eq("user_id", userId)
				.eq("is_delete", 0)
				.last("limit 1"));

		Assert.notNull(order, "订单信息不存在");
		// 订单已取消
		if (order.getOrderStatus() != OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode()) {
			throw new OperateException("待发货状态下才可催发货");
		}
		Long count = orderUrgeMsgMapper.selectCount(new LambdaQueryWrapper<OrderUrgeMsg>().eq(OrderUrgeMsg::getOrderId, id));
		if(count <= 0) {
			List<OrderGoods> list = orderGoodsMapper.selectList(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId, id)
					.select(OrderGoods::getId,OrderGoods::getShopId));
			list.stream().forEach( goods ->{
				OrderUrgeMsg urge = new OrderUrgeMsg();
				urge.setOrderId(id);
				urge.setOrderSn(order.getOrderSn());
				urge.setUserId(userId);
				urge.setOrderStatus(0);
				urge.setShopId(goods.getShopId());
				urge.setCreateTime(TimeUtils.timestamp());
				urge.setUpdateTime(TimeUtils.timestamp());
				orderUrgeMsgMapper.insert(urge);
			});
		}
	}

	/**
	 * 查询物流
	 *
	 * @author mjf
	 * @param userId Integer
	 * @param id Integer
	 * @return OrderLogisticsVo
	 */
	@Override
	public OrderLogisticsVo logistics(Integer userId, Integer id) {
		Order order = orderMapper.selectOne(new QueryWrapper<Order>()
				.eq("user_id", userId)
				.eq("id", id)
				.last("limit 1"));
		Assert.notNull(order, "订单信息不存在");

		if(order.getExpressIs() != 1) {
			throw new OperateException("订单未发货");
		}

		OrderGoods orderGoods = orderGoodsMapper.selectOne(new QueryWrapper<OrderGoods>()
				.eq("order_id", order.getId())
				.orderByAsc("id")
				.last("limit 1"));

		OrderLogisticsVo vo = new OrderLogisticsVo();
		vo.setGoodsName(orderGoods.getGoodsName());
		vo.setGoodsImage(UrlUtils.toAbsoluteUrl(orderGoods.getGoodsImage()));
		vo.setExpressNo(order.getExpressNo());
		vo.setCreateTime(TimeUtils.timestampToDate(order.getCreateTime()));
		vo.setPayTime(TimeUtils.timestampToDate(order.getPayTime()));
		vo.setExpressTime(TimeUtils.timestampToDate(order.getExpressTime()));
		vo.setContact(order.getAddressContact());
		vo.setMobile(order.getAddressMobile());
		vo.setAddress(order.getAddressContent());
		vo.setOrderGoodsNum(order.getGoodsNum());
		vo.setOrderStatus(order.getOrderStatus());
		vo.setOrderStatusMsg(OrderEnum.getOrderStatusMsg(order.getOrderStatus()));
		vo.setConfirmTime(TimeUtils.timestampToDate(order.getConfirmTime()));

		if(order.getExpressId() < 0 || StringUtils.isEmpty(order.getExpressNo())) {
			throw new OperateException("订单无需物流");
		}

		try {
			String expressEngine = ConfigUtils.get("logistics", "engine", "");
			if (StringUtils.isEmpty(expressEngine)) {
				throw new OperateException("请联系管理员配置物流设置");
			}
			// 物流公司
			ExpressCompany expressCompany = expressCompanyMapper.selectById(order.getExpressId());
			vo.setExpressName(expressCompany.getName());

			// 快递查询参数
			KdQueryTrackParam kdQueryTrackParam = new KdQueryTrackParam();
			// 物流公司编码
			String expressCode = expressCompany.getCodeKdniao();
			if(expressEngine.equals("kd100")) {
				expressCode = expressCompany.getCodeKd100();
				if (expressCode.equals("SF") || expressCode.equals("sf") || expressCode.equals("shunfeng")) {
					kdQueryTrackParam.setPhone(order.getAddressMobile());
				}
			} else {
				if (expressCode.equals("SF")) {
					kdQueryTrackParam.setPhone(order.getAddressMobile().substring(order.getAddressMobile().length() - 4));
				}
			}

			kdQueryTrackParam.setCom(expressCode);
			kdQueryTrackParam.setNum(order.getExpressNo());
			List<KdTrackResultVo> track = (new DeliveryDriver()).queryTrack(kdQueryTrackParam);
			// 物流信息
			vo.setTrack(track);
		} catch (OperateException e) {
			// 查询中错误信息
			vo.setTrackError(e.getMsg());
		}
		return vo;
	}

	/**
	 * 系统取消时间
	 *
	 * @author mjf
	 * @return Long
	 */
	@Override
	public Long getCancelUnpaidOrderTime(Long orderCreateTime) {
		// 系统自动取消订单时间
		float cancelTimeConfig = Float.parseFloat(ConfigUtils.get("trade", "cancelUnpaidOrderTime", "-1"));
		long cancelUnpaidOrderTime = 0;
		if (cancelTimeConfig != -1) {
			cancelUnpaidOrderTime = (long)(cancelTimeConfig * 60);
			long diff = (orderCreateTime + cancelUnpaidOrderTime) - TimeUtils.timestamp();
			if (diff <= 0) {
				cancelUnpaidOrderTime = 0;
			} else {
				cancelUnpaidOrderTime = diff;
			}
		}
		return cancelUnpaidOrderTime;
	}

	/**
	 * 获取订单商品信息
	 *
	 * @author mjf
	 * @param userId Integer
	 * @param orderSettleValidate OrderSettleValidate
	 * @return List<OrderGoodsInfoVo>
	 */
	public List<OrderGoodsInfoVo> getOrderGoodsInfo(Integer userId, OrderSettleValidate orderSettleValidate) {
		// 购买类型
		String buyType = orderSettleValidate.getBuyType();
		// 商品参数
		List<BuyGoodsValidate> buyGoodsValidate = orderSettleValidate.getBuyGoods();
		// 商品信息list
		List<OrderGoodsInfoVo> orderGoodsList = new ArrayList<>();
		// 购物车购买
		if (buyType.equals("cart")) {
			// 购物车Ids
			List<Integer> cartIds = buyGoodsValidate.stream().map(BuyGoodsValidate::getCartId).collect(Collectors.toList());
			if (cartIds.isEmpty()) {
				throw new OperateException("请选择商品");
			}

			// 商品信息
			orderGoodsList = goodsMapper.selectJoinList(OrderGoodsInfoVo.class, new MPJQueryWrapper<Goods>()
					.eq("t.is_delete", 0)
					.eq("c.is_delete", 0)
					.eq("user_id", userId)
					.in("c.id", cartIds)
					.innerJoin("?_cart c ON c.goods_id = t.id".replace("?_", GlobalConfig.tablePrefix))
					.innerJoin("?_goods_sku GS ON GS.id = c.goods_sku_id".replace("?_", GlobalConfig.tablePrefix))
					.select("t.code as goods_code,t.express_type,t.express_template_id,t.image,t.name as goods_name,t.status," +
							"GS.goods_id,GS.id as goods_sku_id,GS.image as sku_image,GS.sku_value_arr," +
							"GS.stock,GS.price,GS.price as original_price,GS.weight,GS.volume,c.num"
							+ ",GS.market_price,t.commission_type,t.cashback_ratio,t.commission_ratio"));

			Assert.notEmpty(orderGoodsList, "商品信息不存在");

			for (OrderGoodsInfoVo goodsInfoVo : orderGoodsList) {
				goodsInfoVo.setGoodsType(OrderGoodsEnum.GOODS_TYPE_NORMAL.getCode());
				// 计算金币价格
				BigDecimal price = BigDecimal.ZERO;
				// 计算产品类型且分佣金额
				if(null != goodsInfoVo.getCashbackRatio() && goodsInfoVo.getCashbackRatio().compareTo(BigDecimal.ZERO) > 0) {
					if(goodsInfoVo.getCommissionType() == 1) {	// 利润 【产品售价-产品供货价-领券优惠金额】
						price = goodsInfoVo.getPrice().subtract(goodsInfoVo.getMarketPrice()).subtract(BigDecimal.ZERO);

					}else {	// 差价 【产品售价*百分比（如5%）-领券优惠金额】
						BigDecimal divide = goodsInfoVo.getCommissionRatio().divide(hundred,2, RoundingMode.HALF_UP);
						BigDecimal multiply = goodsInfoVo.getPrice().multiply(divide);
						price = multiply.subtract(BigDecimal.ZERO);
					}
				}
				// 返现金币
//				goodsInfoVo.setGoldCoin(price.multiply(hundred));
				goodsInfoVo.setGoldCoin(cashbackAdd(goodsInfoVo, price));
			}

		} else {
			// 立即购买只有一个商品
			BuyGoodsValidate buyNowGoods = buyGoodsValidate.get(0);
			// 商品信息
			OrderGoodsInfoVo oneOrderGoods = goodsMapper.selectJoinOne(OrderGoodsInfoVo.class, new MPJQueryWrapper<Goods>()
					.eq("t.is_delete", 0)
					.eq("GS.id", buyNowGoods.getSkuId())
					.innerJoin("?_goods_sku GS ON GS.goods_id=t.id".replace("?_", GlobalConfig.tablePrefix))
					.select("t.code as goods_code,t.express_type,t.express_template_id,t.image,t.name as goods_name,t.status," +
							"GS.goods_id,GS.id as goods_sku_id,GS.image as sku_image,GS.sku_value_arr," +
							"GS.stock,GS.price,GS.price as original_price,GS.weight,GS.volume"
							+ ",GS.market_price,t.commission_type,t.cashback_ratio,t.commission_ratio")
					.last("limit 1"));

			if (oneOrderGoods == null) {
				throw new OperateException("商品信息不存在");
			}

			// 立即购买只有一个商品
			oneOrderGoods.setNum(buyGoodsValidate.get(0).getNum());
			oneOrderGoods.setGoodsType(OrderGoodsEnum.GOODS_TYPE_NORMAL.getCode());
			
			// 计算金币价格
			BigDecimal price = BigDecimal.ZERO;
			// 计算产品类型且分佣金额
			if(null != oneOrderGoods.getCashbackRatio() && oneOrderGoods.getCashbackRatio().compareTo(BigDecimal.ZERO) > 0) {
				if(oneOrderGoods.getCommissionType() == 1) {	// 利润 【产品售价-产品供货价-领券优惠金额】
					price = oneOrderGoods.getPrice().subtract(oneOrderGoods.getMarketPrice()).subtract(BigDecimal.ZERO);

				}else {	// 差价 【产品售价*百分比（如5%）-领券优惠金额】
					BigDecimal divide = oneOrderGoods.getCommissionRatio().divide(hundred,2, RoundingMode.HALF_UP);
					BigDecimal multiply = oneOrderGoods.getPrice().multiply(divide);
					price = multiply.subtract(BigDecimal.ZERO);
				}
			}
			// 返现金币
			oneOrderGoods.setGoldCoin(cashbackAdd(oneOrderGoods, price));

			// 秒杀活动
			if (buyNowGoods.getSeckillId() != null && buyNowGoods.getSeckillId() > 0) {
				SeckillGoodsSku seckillGoodsSku = this.__getSeckillGoodsSku(buyNowGoods);
				if (seckillGoodsSku != null) {
					oneOrderGoods.setPrice(seckillGoodsSku.getSeckillPrice());
					oneOrderGoods.setGoodsType(OrderGoodsEnum.GOODS_TYPE_SECKILL.getCode());
				}
			}
			orderGoodsList.add(oneOrderGoods);
		}

		for (OrderGoodsInfoVo goodsInfoVo : orderGoodsList) {
			if (goodsInfoVo.getStatus() == 0) {
				throw new OperateException("商品:" + goodsInfoVo.getGoodsName() + " 已经下架，请选择商品下单");
			}
			if (goodsInfoVo.getNum() <= 0 || goodsInfoVo.getStock() < goodsInfoVo.getNum()) {
				throw new OperateException("商品:" + goodsInfoVo.getGoodsName() + " 当前库存仅剩:" + goodsInfoVo.getStock());
			}
			BigDecimal itemGoodsAmount = goodsInfoVo.getPrice().multiply(BigDecimal.valueOf(goodsInfoVo.getNum()));
			goodsInfoVo.setGoodsAmount(itemGoodsAmount);
			goodsInfoVo.setImage(UrlUtils.toAbsoluteUrl(goodsInfoVo.getImage()));
			goodsInfoVo.setCouponMoney(BigDecimal.ZERO);
			goodsInfoVo.setExpressMoney(BigDecimal.ZERO);
		}

		return orderGoodsList;
	}

	/**
	 * 运费计算
	 *
	 * @author mjf
	 * @param orderGoodsList List<OrderGoodsInfoVo>
	 * @return BigDecimal
	 */
	public BigDecimal calculateFreight(List<OrderGoodsInfoVo> orderGoodsList) {
		BigDecimal totalFreight = BigDecimal.ZERO;
		for (OrderGoodsInfoVo goodsInfoVo : orderGoodsList) {
			// 运费
			BigDecimal expressMoney = BigDecimal.ZERO;

			// 设置单个商品运费
			goodsInfoVo.setExpressMoney(expressMoney);

			// 1=包邮 2=运费模板
			if (1 == goodsInfoVo.getExpressType()) {
				continue;
			}

			// 运费模板
			ExpressTpl expressTpl = expressTplMapper.selectOne(new QueryWrapper<ExpressTpl>()
					.eq("id", goodsInfoVo.getExpressTemplateId())
					.eq("is_delete", 0)
					.last("limit 1"));
			if (expressTpl == null) {
				continue;
			}

			// 商品比较单位
			Double unit = 0.0;
			switch (expressTpl.getType()) {
			//按件计费
			case 0:
				unit = Double.valueOf(goodsInfoVo.getNum());
				break;
				//重量计费
			case 1:
				unit = goodsInfoVo.getWeight();
				break;
				//体积计费
			case 2:
				unit = goodsInfoVo.getVolume();
				break;
			}

			// 首(重/件/立方)
			Integer firstNum = expressTpl.getFirstNum();
			if (unit <= firstNum) {
				// 小于首重，仅付首重金额
				expressMoney = expressTpl.getFirstPrice();
			} else {
				// 减去首重后的重量 / 续重
				int left = (int) Math.ceil((unit - firstNum) / (double) expressTpl.getContinueNum());
				// 续重需付金额
				BigDecimal continuePrice = expressTpl.getContinuePrice().multiply(BigDecimal.valueOf(left));
				// 首重金额 + 续重金额
				expressMoney = expressTpl.getFirstPrice().add(continuePrice);
			}

			// 设置单个商品运费
			goodsInfoVo.setExpressMoney(expressMoney);
			// 订单总运费
			totalFreight = totalFreight.add(expressMoney);
		}
		return totalFreight;
	}

	/**
	 * 优惠券优惠金额
	 *
	 * @author mjf
	 * @param orderGoodsList List<OrderGoodsInfoVo>
	 * @param couponListId Integer
	 * @return BigDecimal
	 */
	public BigDecimal calculateCoupon(List<OrderGoodsInfoVo> orderGoodsList, List<Integer> couponListId, Integer userId) {
		// 总优惠金额
		BigDecimal totalDiscountMoney = BigDecimal.ZERO;

		if (couponListId == null || couponListId.size() <= 0) {
			return totalDiscountMoney;
		}
		BigDecimal couponTotalAmoun = BigDecimal.ZERO;
		for (Integer item : couponListId) {
			// 优惠券领取记录
			CouponList couponList = couponListMapper.selectOne(new QueryWrapper<CouponList>()
					.eq("coupon_id", item)
					.eq("user_id", userId)
					.orderByDesc("create_time")
					.last("limit 1"));

			Assert.notNull(couponList, "优惠券不可用");
			if (TimeUtils.timestamp() > couponList.getInvalidTime()
					|| couponList.getStatus() != CouponEnum.USE_STATUS_NOT.getCode()) {
				throw new OperateException("优惠券已失效");
			}

			// 优惠券
			Coupon coupon = couponMapper.selectById(couponList.getCouponId());
			Assert.notNull(coupon, "优惠券不可用");

			couponTotalAmoun = couponTotalAmoun.add(coupon.getMoney());
			// 优惠券 商品id
			List<Integer> couponGoodsIds = new ArrayList<>();
			if (StringUtils.isNoneBlank(coupon.getUseGoodsIds())) {
				couponGoodsIds = ListUtils.stringToListAsInt(coupon.getUseGoodsIds(), ",");
			}

			// 可参与优惠券优惠的商品金额
			BigDecimal ableDiscountMoney = BigDecimal.ZERO;
			// 可参与优惠券的商品ID
			List<Integer> ableGoodsIds = new ArrayList<>();
			for (OrderGoodsInfoVo goodsInfoVo : orderGoodsList) {
				// 指定商品可用
				if (coupon.getUseGoodsType() == CouponEnum.USE_GOODS_TYPE_ALLOW.getCode()
						&& !couponGoodsIds.contains(goodsInfoVo.getGoodsId())) {
					continue;
				}
				// 指定商品不可用
				if (coupon.getUseGoodsType() == CouponEnum.USE_GOODS_TYPE_BAN.getCode()
						&& couponGoodsIds.contains(goodsInfoVo.getGoodsId())) {
					continue;
				}
				ableGoodsIds.add(goodsInfoVo.getGoodsId());
				ableDiscountMoney = ableDiscountMoney.add(goodsInfoVo.getGoodsAmount());
			}

			if (coupon.getMoney().compareTo(BigDecimal.ZERO) <= 0 || ableDiscountMoney.compareTo(BigDecimal.ZERO) <= 0) {
				throw new OperateException("优惠券不可用");
			}

			// 满金额使用
			if (coupon.getConditionType() == CouponEnum.CONDITION_TYPE_FULL.getCode()
					&& ableDiscountMoney.compareTo(coupon.getConditionMoney()) < 0) {
				throw new OperateException("当前商品不满足优惠券使用金额");
			}

			for (int i = 0; i < orderGoodsList.size(); i++) {
				// 非可用商品
				if (!ableGoodsIds.contains(orderGoodsList.get(i).getGoodsId())) {
					continue;
				}

				// 订单商品可获得优惠金额
				BigDecimal itemDiscountMoney = orderGoodsList.get(i).getGoodsAmount().divide(ableDiscountMoney, 2, RoundingMode.HALF_UP).multiply(coupon.getMoney());

				// 当前是否为最后一个商品
				if (i == orderGoodsList.size() - 1) {
					itemDiscountMoney = couponTotalAmoun.subtract(totalDiscountMoney);
				}

				// 当前可获得的优惠大于订单商品时
				if (itemDiscountMoney.compareTo(orderGoodsList.get(i).getGoodsAmount()) > 0) {
					itemDiscountMoney = orderGoodsList.get(i).getGoodsAmount();
				}

				orderGoodsList.get(i).setCouponMoney(orderGoodsList.get(i).getCouponMoney().add(itemDiscountMoney));

				totalDiscountMoney = totalDiscountMoney.add(itemDiscountMoney);
			}


		}
		return totalDiscountMoney;
	}

	/**
	 * 提交订单
	 *
	 * @author mjf
	 * @param settleResultVo OrderSettleResultVo
	 * @param userId Integer
	 * @return SubmitOrderResultVo
	 */
	@Transactional
	public Order addOrder(OrderSettleResultVo settleResultVo, Integer userId) {
		// 订单商品信息
		List<OrderGoodsInfoVo> orderGoodsList = settleResultVo.getGoods();
		// 用户地址
		UserAddressVo userAddress = settleResultVo.getAddress();
		Assert.notNull(userAddress, "请选择收货地址");

		// 订单编号
		String orderSn = orderMapper.randMakeOrderSn("order_sn");

		// 订单
		Order order = new Order();
		order.setToUserId(settleResultVo.getToUserId());
		order.setOrderSn(orderSn);
		order.setUserId(userId);
		order.setOrderSource(LikeFrontThreadLocal.getTerminal());
		order.setOrderType(settleResultVo.getOrderType());
		order.setOrderStatus(OrderEnum.ORDER_STATUS_WAIT_PAY.getCode());
		order.setAddress(JSONArray.toJSONString(userAddress));
		order.setAddressContact(userAddress.getContact());
		order.setAddressMobile(userAddress.getMobile());
		order.setAddressContent(userAddress.getAddressDetail());
		order.setMoney(settleResultVo.getTotalAmount());
		order.setGoodsMoney(settleResultVo.getGoodsAmount());
		order.setCouponMoney(settleResultVo.getCouponAmount());
		order.setExpressMoney(settleResultVo.getFreightAmount());
		order.setNeedPayMoney(settleResultVo.getOrderAmount());
		order.setGoodsNum(settleResultVo.getTotalNum());
		order.setUserRemark(settleResultVo.getRemark() != null ? settleResultVo.getRemark() : "");
		order.setSeckillId(settleResultVo.getSeckillId());
		order.setUpdateTime(System.currentTimeMillis() / 1000);
		order.setCreateTime(System.currentTimeMillis() / 1000);
		order.setShopId(goodsMapper.selectOne(new LambdaQueryWrapper<Goods>().eq(Goods::getId, orderGoodsList.get(0).getGoodsId()).select(Goods::getShopId)).getShopId());
		order.setMainOrder(0);
		if(settleResultVo.getCouponListId()!=null&&settleResultVo.getCouponListId().size()>0){
			StringBuilder stringBuilder = new StringBuilder();
			settleResultVo.getCouponListId().forEach(item->{
				stringBuilder.append(item+",");
			});
			order.setCouponListId(stringBuilder.substring(0,stringBuilder.length()-1));
		}else {
			order.setCouponListId("0");
		}
		//查询当前是否绑定上级
		QueryWrapper<User> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("id",userId);
		User user = userMapper.selectOne(queryWrapper);
		if (user!=null){
			order.setIsBind(1);
			order.setBindId(user.getInviterId());
		}

		orderMapper.insert(order);

		//添加子订单
		for(OrderGoodsInfoVo orderGoodsInfoVo:orderGoodsList){
			orderSn = orderMapper.randMakeOrderSn("order_sn");
			// 订单
			Order orderSub = new Order();
			orderSub.setToUserId(settleResultVo.getToUserId());
			orderSub.setOrderSn(orderSn);
			orderSub.setUserId(userId);
			orderSub.setOrderSource(LikeFrontThreadLocal.getTerminal());
			orderSub.setOrderType(settleResultVo.getOrderType());
			orderSub.setOrderStatus(OrderEnum.ORDER_STATUS_WAIT_PAY.getCode());
			orderSub.setAddress(JSONArray.toJSONString(userAddress));
			orderSub.setAddressContact(userAddress.getContact());
			orderSub.setAddressMobile(userAddress.getMobile());
			orderSub.setAddressContent(userAddress.getAddressDetail());
			orderSub.setMoney(orderGoodsInfoVo.getOriginalPrice());
			orderSub.setGoodsMoney(orderGoodsInfoVo.getPrice());
			orderSub.setCouponMoney(orderGoodsInfoVo.getCouponMoney());
			orderSub.setExpressMoney(orderGoodsInfoVo.getExpressMoney());
			orderSub.setNeedPayMoney(orderGoodsInfoVo.getGoodsAmount());
			orderSub.setGoodsNum(settleResultVo.getTotalNum());
			orderSub.setUserRemark(settleResultVo.getRemark() != null ? settleResultVo.getRemark() : "");
			orderSub.setSeckillId(settleResultVo.getSeckillId());
			orderSub.setUpdateTime(System.currentTimeMillis() / 1000);
			orderSub.setCreateTime(System.currentTimeMillis() / 1000);
			orderSub.setShopId(goodsMapper.selectOne(new LambdaQueryWrapper<Goods>().eq(Goods::getId, orderGoodsList.get(0).getGoodsId()).select(Goods::getShopId)).getShopId());
			orderSub.setMainOrder(1);
			orderSub.setMainId(order.getOrderSn());
			if(settleResultVo.getCouponListId()!=null&&settleResultVo.getCouponListId().size()>0){
				StringBuilder stringBuilder = new StringBuilder();
				settleResultVo.getCouponListId().forEach(item->{
					stringBuilder.append(item+",");
				});
				orderSub.setCouponListId(stringBuilder.substring(0,stringBuilder.length()-1));
			}else {
				orderSub.setCouponListId("0");
			}
			//查询当前是否绑定上级
			QueryWrapper<User> queryWrapperSub=new QueryWrapper<>();
			queryWrapperSub.eq("id",userId);
			User users = userMapper.selectOne(queryWrapperSub);
			if (users!=null){
				orderSub.setIsBind(1);
				orderSub.setBindId(users.getInviterId());
			}
			orderMapper.insert(orderSub);
			//添加子订单商品信息
			OrderGoods orderGoods = new OrderGoods();
			orderGoods.setShopId(goodsMapper.selectOne(new LambdaQueryWrapper<Goods>().eq(Goods::getId, orderGoodsInfoVo.getGoodsId()).select(Goods::getShopId)).getShopId());
			orderGoods.setUserId(userId);
			orderGoods.setToUserId(settleResultVo.getToUserId());
			orderGoods.setShareUserId(settleResultVo.getShareUserId());
			orderGoods.setOrderId(orderSub.getId());
			orderGoods.setPayMoney(BigDecimal.valueOf(0.00));
			orderGoods.setGoodsType(orderGoodsInfoVo.getGoodsType());
			orderGoods.setGoodsId(orderGoodsInfoVo.getGoodsId());
			orderGoods.setGoodsName(orderGoodsInfoVo.getGoodsName());
			orderGoods.setGoodsImage(UrlUtils.toRelativeUrl(orderGoodsInfoVo.getImage()));
			orderGoods.setGoodsCode(orderGoodsInfoVo.getGoodsCode());
			orderGoods.setGoodsSkuId(orderGoodsInfoVo.getGoodsSkuId());
			orderGoods.setGoodsSkuValue(orderGoodsInfoVo.getSkuValueArr());
			// 商品单价
			orderGoods.setGoodsOriginalPrice(orderGoodsInfoVo.getOriginalPrice());
			orderGoods.setGoodsPrice(orderGoodsInfoVo.getPrice());
			orderGoods.setGoodsNum(orderGoodsInfoVo.getNum());
			// 商品总额
			orderGoods.setGoodsMoney(orderGoodsInfoVo.getGoodsAmount());
			// 商品运费
			orderGoods.setExpressMoney(orderGoodsInfoVo.getExpressMoney());
			// 优惠金额
			orderGoods.setCouponMoney(orderGoodsInfoVo.getCouponMoney());
			// 订单总额 商品总额 + 运费
			orderGoods.setMoney(orderGoodsInfoVo.getGoodsAmount().add(orderGoodsInfoVo.getExpressMoney()));
			// 商品应付总额 商品总额 + 运费
			orderGoods.setNeedPayMoney(orderGoodsInfoVo.getGoodsAmount().add(orderGoodsInfoVo.getExpressMoney()).subtract(orderGoodsInfoVo.getCouponMoney()));
			orderGoods.setAfterSale(OrderGoodsEnum.AFTER_STATUS_NO.getCode());
			orderGoods.setCreateTime(System.currentTimeMillis() / 1000);
			orderGoods.setUpdateTime(System.currentTimeMillis() / 1000);
			// 商户所得金额
			GoodsSku goodsSku = goodsSkuMapper.selectById(orderGoodsInfoVo.getGoodsSkuId());
			if(null != goodsSku && null != goodsSku.getMarketPrice()) {
				orderGoods.setMarketPrice(goodsSku.getMarketPrice().multiply(BigDecimal.valueOf(orderGoodsInfoVo.getNum())));
			}
			orderGoodsMapper.insert(orderGoods);
		}


		for (OrderGoodsInfoVo orderGoodsListVo : orderGoodsList) {
			OrderGoods orderGoods = new OrderGoods();
			orderGoods.setShopId(goodsMapper.selectOne(new LambdaQueryWrapper<Goods>().eq(Goods::getId, orderGoodsListVo.getGoodsId()).select(Goods::getShopId)).getShopId());
			orderGoods.setUserId(userId);
			orderGoods.setToUserId(settleResultVo.getToUserId());
			orderGoods.setShareUserId(settleResultVo.getShareUserId());
			orderGoods.setOrderId(order.getId());
			orderGoods.setPayMoney(BigDecimal.valueOf(0.00));
			orderGoods.setGoodsType(orderGoodsListVo.getGoodsType());
			orderGoods.setGoodsId(orderGoodsListVo.getGoodsId());
			orderGoods.setGoodsName(orderGoodsListVo.getGoodsName());
			orderGoods.setGoodsImage(UrlUtils.toRelativeUrl(orderGoodsListVo.getImage()));
			orderGoods.setGoodsCode(orderGoodsListVo.getGoodsCode());
			orderGoods.setGoodsSkuId(orderGoodsListVo.getGoodsSkuId());
			orderGoods.setGoodsSkuValue(orderGoodsListVo.getSkuValueArr());
			// 商品单价
			orderGoods.setGoodsOriginalPrice(orderGoodsListVo.getOriginalPrice());
			orderGoods.setGoodsPrice(orderGoodsListVo.getPrice());
			orderGoods.setGoodsNum(orderGoodsListVo.getNum());
			// 商品总额
			orderGoods.setGoodsMoney(orderGoodsListVo.getGoodsAmount());
			// 商品运费
			orderGoods.setExpressMoney(orderGoodsListVo.getExpressMoney());
			// 优惠金额
			orderGoods.setCouponMoney(orderGoodsListVo.getCouponMoney());
			// 订单总额 商品总额 + 运费
			orderGoods.setMoney(orderGoodsListVo.getGoodsAmount().add(orderGoodsListVo.getExpressMoney()));
			// 商品应付总额 商品总额 + 运费
			orderGoods.setNeedPayMoney(orderGoodsListVo.getGoodsAmount().add(orderGoodsListVo.getExpressMoney()).subtract(orderGoodsListVo.getCouponMoney()));
			orderGoods.setAfterSale(OrderGoodsEnum.AFTER_STATUS_NO.getCode());
			orderGoods.setCreateTime(System.currentTimeMillis() / 1000);
			orderGoods.setUpdateTime(System.currentTimeMillis() / 1000);
			orderGoodsMapper.insert(orderGoods);
		}

		// 订单日志
		logOrderMapper.add(order.getId(),
				OrderLogEnum.TYPE_USER.getCode(),
				OrderLogEnum.CHANNEL_ADD_ORDER.getCode(),
				userId, OrderLogEnum.CHANNEL_ADD_ORDER.getMsg());

		return order;
	}

	/**
	 * 删除购物车
	 *
	 * @author mjf
	 * @param buyType String
	 * @param buyGoodsValidate List<BuyGoodsValidate>
	 */
	private void __deleteCart(String buyType, List<BuyGoodsValidate> buyGoodsValidate) {
		if (buyType.equals("cart")) {
			for (BuyGoodsValidate buyGoods : buyGoodsValidate) {
				Cart cart = new Cart();
				cart.setId(buyGoods.getCartId());
				cart.setIsDelete(1);
				cart.setUpdateTime(System.currentTimeMillis() / 1000);
				cartMapper.updateById(cart);
			}
		}
	}

	/**
	 * 扣除库存
	 *
	 * @author mjf
	 * @param orderGoodsList List<OrderGoodsInfoVo>
	 */
	private void __updateGoodsStock(List<OrderGoodsInfoVo> orderGoodsList) {
		int inventoryOccupancy = Integer.parseInt(ConfigUtils.get("trade","inventoryOccupancy", "1"));
		// 订单提交时占用库存
		if (inventoryOccupancy == 1) {
			for (OrderGoodsInfoVo orderGoodsVo : orderGoodsList) {
				// 扣除商品规格库存
				goodsSkuMapper.update(null, new UpdateWrapper<GoodsSku>()
						.eq("id", orderGoodsVo.getGoodsSkuId())
						.setSql("stock = IF(stock-" + orderGoodsVo.getNum() + "<0, 0, stock-" + orderGoodsVo.getNum() + ")"));
				// 扣除商品总库存
				goodsMapper.update(null, new UpdateWrapper<Goods>()
						.eq("id", orderGoodsVo.getGoodsId())
						.setSql("total_stock = IF(total_stock-" + orderGoodsVo.getNum() + "<0, 0, total_stock-" + orderGoodsVo.getNum() + ")"));
			}
		}
	}

	/**
	 * 更新优惠券记录
	 *
	 * @author mjf
	 * @param couponListId Integer
	 * @param orderId Integer
	 * @param userId Integer
	 */
	private void __updateCouponList(List<Integer> couponListId, Integer orderId, Integer userId) {
		if (couponListId != null && couponListId.size() > 0) {
			couponListId.forEach(item->{
				CouponList couponList = couponListMapper.selectOne(new QueryWrapper<CouponList>()
						.eq("id", item)
						.eq("user_id", userId)
						.last("limit 1"));

				if (couponList != null) {
					couponList.setOrderId(orderId);
					couponList.setStatus(CouponEnum.USE_STATUS_OK.getCode());
					couponList.setUseTime(System.currentTimeMillis() / 1000);
					couponList.setUpdateTime(System.currentTimeMillis() / 1000);
					couponListMapper.updateById(couponList);
				}
			});

		}
	}



	/**
	 * 	售后详情按钮
	 * @param order
	 * @return
	 */
	private Integer __afterSalesBtn(Order order) {
		int btn = 0;
		if(order.getOrderStatus() != 4) {
			if (order.getOrderStatus() == OrderEnum.ORDER_STATUS_REFUND.getCode() || order.getOrderStatus() == OrderEnum.ORDER_STATUS_REFUND_SUCCESS.getCode()
					|| order.getOrderStatus() == OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode()) {
				btn = 1;
			}
		}
		return btn;
	}

	/**
	 * 	分享按钮
	 * @param order
	 * @return
	 */
	private Integer __shareBtn(Order order) {
		int btn = 0;
		if (order.getOrderStatus() == OrderEnum.ORDER_STATUS_COMPLETED.getCode()) {
			btn = 1;
		}
		return btn;
	}


	/**
	 * 	催发货按钮
	 * @param order
	 * @return
	 */
	private Integer __urgeBtn(Order order) {
		int btn = 0;
		if (order.getOrderStatus() == OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode()) {
			btn = 1;
		}
		return btn;
	}


	/**
	 * 支付按钮
	 *
	 * @author mjf
	 * @param order Order
	 * @return Integer
	 */
	private Integer __payBtn(Order order) {
		int btn = 0;
		if (order.getOrderStatus() == OrderEnum.ORDER_STATUS_WAIT_PAY.getCode()) {
			btn = 1;
		}
		return btn;
	}

	/**
	 * 取消按钮
	 *
	 * @author mjf
	 * @param order Order
	 * @return Integer
	 */
	private Integer __cancelBtn(Order order) {
		int btn = 0;
		// 未支付
		if (order.getOrderStatus() == OrderEnum.ORDER_STATUS_WAIT_PAY.getCode()
				|| order.getOrderStatus() == OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode()
				|| order.getOrderStatus() == OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode()) {
			btn = 1;
			return btn;
		}
		// 待发货
		if (OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode() == order.getOrderStatus()) {
			// 订单允许取消时间
			float cancelTimeConfig = Float.parseFloat(ConfigUtils.get("trade", "cancelUnshippedOrderTime", "-1"));
			if (cancelTimeConfig == -1) {
				btn = 0;
			} else {
				if (TimeUtils.timestamp() > (order.getPayTime() + (long)(cancelTimeConfig * 60))) {
					btn = 0;
				}
			}
		}
		return btn;
	}

	/**
	 * 确定按钮
	 *
	 * @author mjf
	 * @param order Order
	 * @return Integer
	 */
	private Integer __confirmBtn(Order order) {
		int btn = 0;
		if (OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode() == order.getOrderStatus()) {
			btn = 1;
		}
		return btn;
	}

	/**
	 * 删除按钮
	 *
	 * @author mjf
	 * @param order Order
	 * @return Integer
	 */
	private Integer __deleteBtn(Order order) {
		int btn = 0;
		if (OrderEnum.ORDER_STATUS_COMPLETED.getCode() == order.getOrderStatus() ||
				OrderEnum.ORDER_STATUS_CANCEL.getCode() == order.getOrderStatus()) {
			btn = 1;
		}
		return btn;
	}

	/**
	 * 查看物流按钮
	 *
	 * @author mjf
	 * @param order Order
	 * @return Integer
	 */
	private Integer __logisticsBtn(Order order) {
		int btn = 0;
		if ((OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode() == order.getOrderStatus() || OrderEnum.ORDER_STATUS_COMPLETED.getCode() == order.getOrderStatus())
				&& 1 == order.getExpressIs()) {
			btn = 1;
		}
		return btn;
	}

	/**
	 * 申请退款按钮
	 *
	 * @author mjf
	 * @param order Order
	 * @return Integer
	 */
	private Integer __refundBtn(Order order) {
		int btn = 0;
		// && (confirm_time + 5 * 60) <= System.currentTimeMillis() / 1000
		if ((OrderEnum.ORDER_STATUS_COMPLETED.getCode() == order.getOrderStatus() || OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode() == order.getOrderStatus())
				&& order.getAfterDeadline() > TimeUtils.timestamp()) {
			// 查询是否有发生售后，没发生则 可显示申请退款按钮
			OrderAfter orderAfter = orderAfterMapper.selectOne(new QueryWrapper<OrderAfter>()
					.in("after_status", Arrays.asList(OrderAfterEnum.AFTER_STATUS_ING.getCode(), OrderAfterEnum.AFTER_STATUS_SUCCESS.getCode()))
					.eq("order_id", order.getId())
					.last("limit 1"));
			Long maxTime = order.getConfirmTime() + 60 * 60 * 24 * 7;
			if (orderAfter == null && maxTime >= System.currentTimeMillis() / 1000 && order.getOrderStatus() != 4) {
				btn = 1;
			}
		}
		System.out.println("btn  " + btn);
		return btn;
	}


	/**
	 * 评价按钮
	 *
	 * @author mjf
	 * @param order Order
	 * @return Integer
	 */
	private Integer __commentBtn(Order order) {
		int btn = 0;
		if (OrderEnum.ORDER_STATUS_COMPLETED.getCode() == order.getOrderStatus() && 1 == order.getPayIs()) {
			btn = 1;
			// 查询订单商品
			List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>()
					.select("id,is_comment")
					.eq("order_id", order.getId()));
			int commentCount = 0;
			for (OrderGoods orderGoods : orderGoodsList) {
				if (orderGoods.getIsComment() == 1) {
					commentCount += 1;
				}
			}
			if (commentCount == orderGoodsList.size()) {
				btn = 0;
			}
		}
		return btn;
	}

	/**
	 * 订单商品售后按钮
	 *
	 * @author mjf
	 * @param order Order
	 * @param orderGoodsId Integer
	 * @return Integer
	 */
	private Integer __afterApplyBtn(Order order, Integer orderGoodsId) {
		int btn = 0;
		// 待支付，已取消 不显示
		if (order.getOrderStatus() == OrderEnum.ORDER_STATUS_WAIT_PAY.getCode()
				|| order.getOrderStatus() == OrderEnum.ORDER_STATUS_CANCEL.getCode()) {
			return btn;
		}

		// 订单是否可以取消,是否在取消时间内
		float cancelTimeConfig = Float.parseFloat(ConfigUtils.get("trade", "cancelUnshippedOrderTime", "-1"));
		if (cancelTimeConfig != -1 && order.getOrderStatus() < OrderEnum.ORDER_STATUS_COMPLETED.getCode()) {
			// 未过可取消时间
			if (TimeUtils.timestamp() < (order.getPayTime() + (long)(cancelTimeConfig * 60))) {
				return btn;
			}
		}

		// 当前是否在售后时间内(买家售后维权时效: -1=关闭,否则开启(天))
		float afterSalesDay = Float.parseFloat(ConfigUtils.get("trade", "afterSalesDay", "-1"));
		long ableAfterSalesTime = afterSalesDay != -1 ? (long) (afterSalesDay * 24 * 60 * 60) : 0;
		if (order.getConfirmTime() > 0 && TimeUtils.timestamp() > (order.getConfirmTime() + ableAfterSalesTime)) {
			return btn;
		}

		// 查询是否已申请售后售后
		OrderAfterGoods orderAfterGoods = orderAfterGoodsMapper.selectOne(new QueryWrapper<OrderAfterGoods>()
				.eq("order_goods_id", orderGoodsId)
				.last("limit 1"));

		if (orderAfterGoods == null) {
			btn = 1;
		} else {
			OrderAfter orderAfter = orderAfterMapper.selectById(orderAfterGoods.getOrderAfterId());
			if (orderAfter.getAfterStatus() == OrderAfterEnum.AFTER_STATUS_CLOSE.getCode()) {
				btn = 1;
			}
		}
		return btn;
	}

	/**
	 * 订单商品售后描述
	 *
	 * @author mjf
	 * @param order Order
	 * @param orderGoodsId Integer
	 * @return String
	 */
	private String __afterApplyMsg(Order order, Integer orderGoodsId) {
		String msg = "";
		// 查询是否已申请售后售后
		OrderAfterGoods orderAfterGoods = orderAfterGoodsMapper.selectOne(new QueryWrapper<OrderAfterGoods>()
				.eq("order_goods_id", orderGoodsId)
				.orderByDesc("id")
				.last("limit 1"));

		if (orderAfterGoods != null) {
			// 售后状态
			OrderAfter orderAfter = orderAfterMapper.selectOne(new QueryWrapper<OrderAfter>()
					.eq("id", orderAfterGoods.getOrderAfterId())
					.last("limit 1"));
			msg = OrderAfterEnum.getAfterStatusMsg(orderAfter.getAfterStatus());

			// 订单取消不显示售后描述
			if (order.getOrderStatus().equals(OrderEnum.ORDER_STATUS_CANCEL.getCode())) {
				msg = "";
			}
		}
		return msg;
	}

	/**
	 * 售后时间
	 *
	 * @author mjf
	 * @return Long
	 */
	private Long __getAfterSaleDeadline() {
		float afterSalesDay = Float.parseFloat(ConfigUtils.get("trade", "afterSalesDay", "-1"));
		long afterSaleDeadline = TimeUtils.timestamp();
		if (afterSalesDay != -1) {
			afterSaleDeadline = (long)(afterSalesDay *24 * 60 * 60) + TimeUtils.timestamp();
		}
		return afterSaleDeadline;
	}

	/**
	 * 取消订单
	 *
	 * @author mjf
	 * @param order Order
	 */
	private void __handleCancelOrder(Order order) {
		TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
		try {
			// 整单售后
			if (order.getPayIs().equals(PaymentEnum.OK_PAID.getCode())) {
				OrderAfter orderAfter = null;
				RefundRecord refundRecord = null;
				RefundLog refundLog = null;
				try {
					//如果是待收货只需要写入售后订单
					if(order.getOrderStatus() == OrderEnum.ORDER_STATUS_TAKE_DELIVER.getCode()){
						// 订单商品信息
						OrderGoods orderGoods = orderGoodsMapper.selectOne(new QueryWrapper<OrderGoods>()
								.eq("order_id", order.getId())
								.last("limit 1"));
						// 校验是否可以申请售后
						OrderAfterCreateValidate orderAfterValidate = new OrderAfterCreateValidate();
						orderAfterValidate.setOrderGoodsId(orderGoods.getId());
						orderAfterValidate.setRefundMoney(order.getPayMoney());
						this.__checkAbleApplyOrderAfter(order.getUserId(), orderAfterValidate);
						// 生成售后日志记录
						String afterSn = orderAfterMapper.randMakeOrderSn("after_sn");
						//OrderAfter orderAfter = new OrderAfter();
						orderAfter = new OrderAfter();
						orderAfter.setAfterSn(afterSn);
						orderAfter.setAfterType(OrderAfterEnum.AFTER_TYPE_GOODS.getCode());
						orderAfter.setUserId(order.getUserId());
						orderAfter.setOrderId(orderGoods.getOrderId());
						orderAfter.setRefundReason("商品已发货，用户未收货取消订单");
						orderAfter.setRefundRemark("商品已发货，用户未收货取消订单");
						orderAfter.setRefundMoney(order.getPayMoney());
						orderAfter.setRefundType(OrderAfterEnum.METHOD_ONLY_REFUND.getCode());// 退款类型 [1=仅退款 2=退货退款]'
						orderAfter.setRefundWay(1); // 退款路径 [1=原路退回]
						orderAfter.setAfterStatus(OrderAfterEnum.AFTER_STATUS_ING.getCode());
						orderAfter.setSubStatus(OrderAfterEnum.SUB_STATUS_ING_WAIT_SELLER_AGREE.getCode());
						orderAfter.setCreateTime(System.currentTimeMillis() / 1000);
						orderAfter.setUpdateTime(System.currentTimeMillis() / 1000);
						// 图片处理
						/*if (!orderAfterValidate.getRefundImage().isEmpty()) {
							StringBuilder refundImage = new StringBuilder();
							for (String image : orderAfterValidate.getRefundImage()) {
								String imageItem = UrlUtils.toRelativeUrl(image) + ",";
								refundImage.append(imageItem);
							}
							orderAfter.setRefundImage(refundImage.substring(0, refundImage.length() - 1));
						}*/
						orderAfterMapper.insert(orderAfter);
						System.out.println("插入数据orderAfter");
						// 售后商品记录
						OrderAfterGoods orderAfterGoods = new OrderAfterGoods();
						orderAfterGoods.setOrderId(orderGoods.getOrderId());
						orderAfterGoods.setOrderGoodsId(orderGoods.getId());
						orderAfterGoods.setOrderAfterId(orderAfter.getId());
						orderAfterGoods.setGoodsId(orderGoods.getGoodsId());
						orderAfterGoods.setGoodsSkuId(orderGoods.getGoodsSkuId());
						orderAfterGoods.setGoodsNum(orderGoods.getGoodsNum());
						orderAfterGoods.setGoodsPrice(orderGoods.getGoodsPrice());
						orderAfterGoods.setRefundMoney(orderGoods.getNeedPayMoney());
						orderAfterGoods.setCreateTime(System.currentTimeMillis() / 1000);
						orderAfterGoods.setUpdateTime(System.currentTimeMillis() / 1000);
						orderAfterGoodsMapper.insert(orderAfterGoods);
						System.out.println("插入数据orderAfterGoods");
						// 售后日志
						logOrderAfterMapper.add(
								LogOrderAfterEnum.TYPE_USER.getCode(),
								order.getUserId(),
								orderAfter.getId(),
								OrderAfterEnum.SUB_STATUS_ING_WAIT_SELLER_AGREE.getMsg()
								);
						System.out.println("插入售后日志");
						// 订单商品 更新状态为售后中 [1=无售后, 2=售后中, 3=售后完成]
						orderGoods.setAfterSale(OrderGoodsEnum.AFTER_STATUS_ING.getCode());
						orderGoodsMapper.updateById(orderGoods);
						System.out.println("修改订单状态1");
						/*OrderAfterCreateVo orderAfterCreateVo = new OrderAfterCreateVo();
						orderAfterCreateVo.setId(orderAfter.getId());
						return orderAfterCreateVo;*/
					}else{
						// 写入售后订单
						String afterSn = orderAfterMapper.randMakeOrderSn("after_sn");
						orderAfter = new OrderAfter();
						orderAfter.setAfterSn(afterSn);
						orderAfter.setUserId(order.getUserId());
						orderAfter.setOrderId(order.getId());
						orderAfter.setRefundWay(1);
						orderAfter.setAfterType(OrderAfterEnum.AFTER_TYPE_ORDER.getCode());
						orderAfter.setRefundType(OrderAfterEnum.METHOD_ONLY_REFUND.getCode());
						orderAfter.setRefundReason(LogOrderAfterEnum.BUYER_CANCEL_ORDER.getMsg());
						orderAfter.setRefundMoney(order.getPayMoney());
						orderAfter.setRefundRemark("系统发起整单退款");
						orderAfter.setAfterStatus(OrderAfterEnum.AFTER_STATUS_ING.getCode());
						orderAfter.setSubStatus(OrderAfterEnum.SUB_STATUS_ING_SELLER_REFUND_ING.getCode());
						orderAfter.setCreateTime(System.currentTimeMillis() / 1000);
						orderAfterMapper.insert(orderAfter);
						// 写入售后商品
						List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().eq("order_id", order.getId()));
						for (OrderGoods item : orderGoodsList) {
							OrderAfterGoods afterGoods = new OrderAfterGoods();
							afterGoods.setOrderId(item.getOrderId());
							afterGoods.setOrderAfterId(orderAfter.getId());
							afterGoods.setOrderGoodsId(item.getId());
							afterGoods.setGoodsId(item.getGoodsId());
							afterGoods.setGoodsSkuId(item.getGoodsSkuId());
							afterGoods.setGoodsNum(item.getGoodsNum());
							afterGoods.setGoodsPrice(item.getGoodsPrice());
							afterGoods.setRefundMoney(item.getPayMoney());
							afterGoods.setCreateTime(System.currentTimeMillis() / 1000);
							afterGoods.setUpdateTime(System.currentTimeMillis() / 1000);
							orderAfterGoodsMapper.insert(afterGoods);
						}
						// 生成售后日志
						Integer roleSeller = LogOrderAfterEnum.TYPE_USER.getCode();
						logOrderAfterMapper.add(roleSeller, order.getUserId(), orderAfter.getId(), LogOrderAfterEnum.BUYER_CANCEL_ORDER.getMsg());
						// 生成退款记录
						String refundSn = refundRecordMapper.randMakeOrderSn("sn");
						refundRecord = new RefundRecord();
						refundRecord.setSn(refundSn);
						refundRecord.setOrderSn(order.getOrderSn());
						refundRecord.setOrderId(order.getId());
						refundRecord.setUserId(order.getUserId());
						refundRecord.setRefundType(RefundEnum.TYPE_USER.getCode());
						refundRecord.setOrderType(RefundEnum.getOrderType(RefundEnum.ORDER_TYPE_ORDER.getCode()));
						refundRecord.setOrderAmount(order.getPayMoney());
						refundRecord.setRefundAmount(orderAfter.getRefundMoney());
						refundRecord.setTransactionId(order.getTransactionId());
						refundRecord.setRefundWay(order.getPayWay());
						refundRecord.setCreateTime(System.currentTimeMillis() / 1000);
						refundRecord.setUpdateTime(System.currentTimeMillis() / 1000);
						refundRecordMapper.insert(refundRecord);
						// 生成退款日志
						refundLog = new RefundLog();
						refundLog.setSn(refundLogMapper.randMakeOrderSn("sn"));
						refundLog.setRecordId(refundRecord.getId());
						refundLog.setUserId(order.getUserId());
						refundLog.setHandleId(0);
						refundLog.setOrderAmount(order.getPayMoney());
						refundLog.setRefundAmount(orderAfter.getRefundMoney());
						refundLog.setRefundStatus(RefundEnum.REFUND_ING.getCode());
						refundLog.setCreateTime(System.currentTimeMillis() / 1000);
						refundLog.setUpdateTime(System.currentTimeMillis() / 1000);
						refundLogMapper.insert(refundLog);
						// 发起退款请求
						switch (order.getPayWay()) {
						case 1: // 余额
							User user = userMapper.selectById(order.getUserId());
							BigDecimal earnings = BigDecimal.ZERO;
							if(user.getEarnings() == null){
								earnings = earnings.add(orderAfter.getRefundMoney());
							}else{
								earnings = user.getEarnings().add(orderAfter.getRefundMoney());
							}
							//user.setMoney(user.getMoney().add(orderAfter.getRefundMoney()));
							user.setEarnings(earnings);
							user.setUpdateTime(System.currentTimeMillis() / 1000);
							userMapper.updateById(user);

							logMoneyMapper.add(
									user.getId(),
									LogMoneyEnum.BNW_INC_CANCEL_ORDER.getCode(),
									order.getPayMoney(),
									order.getId(),
									order.getOrderSn(),
									"售后退还余额!",
									null);
							break;
						case 2: // 微信
							RefundRequestV3 requestV3 = new RefundRequestV3();
							requestV3.setTransactionId(order.getTransactionId());
							requestV3.setOutTradeNo(order.getMainId());
							requestV3.setOutRefundNo(refundSn);
							requestV3.setTotalAmount(AmountUtil.yuan2Fen(order.getPayMoney().toString()));
							requestV3.setRefundAmount(AmountUtil.yuan2Fen(orderAfter.getRefundMoney().toString()));
							WxPayDriver.refund(requestV3);
							break;
						case 3:
							AliPayRefundRequest request = new AliPayRefundRequest();
							request.setTransactionId(order.getTransactionId());
							request.setOutTradeNo(order.getMainId());
							request.setOutRefundNo(refundSn);
							request.setTotalAmount(order.getPayMoney());
							request.setRefundAmount(orderAfter.getRefundMoney());
							AliPayDriver.refund(request);
							break;
						case 4:
							user = userMapper.selectById(order.getUserId());
							BigDecimal integral = BigDecimal.ZERO;
							if(user.getIntegral() == null){
								integral = integral.add(orderAfter.getRefundMoney().multiply(hundred));
							}else{
								integral = user.getIntegral().add(orderAfter.getRefundMoney().multiply(hundred));
							}
							user.setIntegral(integral);
							user.setUpdateTime(System.currentTimeMillis() / 1000);
							userMapper.updateById(user);

							logIntegralMapper.add(
									order.getUserId(), LogMoneyEnum.UI_INC_CANCEL_ORDER.getCode(), integral, order.getId(), order.getOrderSn(), "取消订单退还余额", "");
							break;
						}
						// 退款记录更新
						refundRecord.setRefundStatus(RefundEnum.REFUND_SUCCESS.getCode());
						refundRecord.setUpdateTime(System.currentTimeMillis() / 1000);
						refundRecordMapper.updateById(refundRecord);
						// 退款日志更新
						refundLog.setRefundStatus(RefundEnum.REFUND_SUCCESS.getCode());
						refundLog.setUpdateTime(System.currentTimeMillis() / 1000);
						refundLogMapper.updateById(refundLog);
						// 变更成功状态
						orderAfter.setRefundSn(refundSn);
						orderAfter.setAfterStatus(OrderAfterEnum.AFTER_STATUS_SUCCESS.getCode());
						orderAfter.setSubStatus(OrderAfterEnum.SUB_STATUS_SUCCESS.getCode());
						orderAfter.setUpdateTime(System.currentTimeMillis() / 1000);
						orderAfterMapper.updateById(orderAfter);
					}

				} catch (Exception e) {
					if (StringUtils.isNotNull(orderAfter)) {
						orderAfter.setSubStatus(OrderAfterEnum.SUB_STATUS_ING_SELLER_REFUND_ING.getCode());
						orderAfter.setUpdateTime(System.currentTimeMillis() / 1000);
						orderAfterMapper.updateById(orderAfter);
					}

					if (StringUtils.isNotNull(refundRecord)) {
						refundRecord.setRefundStatus(RefundEnum.REFUND_ERROR.getCode());
						refundRecord.setUpdateTime(System.currentTimeMillis() / (1000));
						refundRecordMapper.updateById(refundRecord);
					}

					if (StringUtils.isNotNull(refundLog)) {
						refundLog.setRefundMsg(e.getMessage());
						refundLog.setRefundStatus(RefundEnum.REFUND_ERROR.getCode());
						refundLog.setUpdateTime(System.currentTimeMillis() / 1000);
						refundLogMapper.updateById(refundLog);
					}

					throw new Exception(e.getMessage());
				}
			}
			// 订单状态-更新为已关闭
			order.setOrderStatus(OrderEnum.ORDER_STATUS_CANCEL.getCode());
			order.setCancelTime(System.currentTimeMillis() / 1000);
			order.setUpdateTime(System.currentTimeMillis() / 1000);
			orderMapper.updateById(order);
			// 订单日志
			Integer channel = OrderLogEnum.CHANNEL_USER_CANCEL_ORDER.getCode();
			logOrderMapper.add(
					order.getId(),
					OrderLogEnum.TYPE_USER.getCode(),
					channel,
					order.getUserId(),
					OrderLogEnum.getValue(channel));
			// 退还库存
			int returnInventory = Integer.parseInt(ConfigUtils.get("trade","returnInventory", "0"));
			if (returnInventory == 1) {
				List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>()
						.eq("order_id", order.getId()));

				for (OrderGoods orderGoods : orderGoodsList) {
					// 退回商品规格库存
					goodsSkuMapper.update(null, new UpdateWrapper<GoodsSku>()
							.eq("id", orderGoods.getGoodsSkuId())
							.setSql("stock = stock + " + orderGoods.getGoodsNum()));
					// 退回商品总库存
					goodsMapper.update(null, new UpdateWrapper<Goods>()
							.eq("id", orderGoods.getGoodsId())
							.setSql("total_stock = total_stock+" + orderGoods.getGoodsNum()));
				}
			}
			// 没有支付的订单取消返回优惠券
			int returnCoupon = Integer.parseInt(ConfigUtils.get("trade","returnCoupon", "0"));
			if (order.getPayIs() == 0 && !StringUtils.isNotNull(order.getCouponListId()) && returnCoupon == 1) {
				this.__returnCoupon(order.getCouponListId());
			}
			// 相关分销订单更新为失效
			DistributionOrder distributionOrder = new DistributionOrder();
			distributionOrder.setStatus(DistributionEnum.ORDER_EXPIRED.getCode());
			distributionOrder.setUpdateTime(System.currentTimeMillis() / 1000);
			distributionOrderMapper.update(distributionOrder, new QueryWrapper<DistributionOrder>()
					.eq("order_id", order.getId()));
			transactionManager.commit(transactionStatus);
		} catch (Exception e) {
			transactionManager.rollback(transactionStatus);
			throw new OperateException(e.getMessage());
		}
	}


	/**
	 * 退回优惠券
	 *
	 * @author mjf
	 * @param couponListId Integer
	 */
	private void __returnCoupon(String couponListId) {
		if (StringUtils.isNotNull(couponListId)) {
			return;
		}
		List<Integer> integerList = Arrays.asList(couponListId.split(",")).stream()
				.map(Integer::parseInt) // 将每个元素从字符串转换为整数
				.collect(Collectors.toList()); // 收集结果到新的列表中

		integerList.forEach(item->{
			CouponList couponList = couponListMapper.selectById(item);
			if (couponList == null) {
				return;
			}

			Coupon coupon = couponMapper.selectById(couponList.getCouponId());
			if (coupon == null) {
				return;
			}

			// 优惠券活动关闭
			if (!coupon.getStatus().equals(CouponEnum.COUPON_STATUS_CONDUCT.getCode())) {
				return;
			}

			// 作废旧优惠券
			couponList.setStatus(CouponEnum.USE_STATUS_VOID.getCode());
			couponList.setUpdateTime(System.currentTimeMillis() / 1000);
			couponListMapper.updateById(couponList);

			String couponCode = couponListMapper.randMakeOrderSn("coupon_code");
			// 发放新优惠券
			CouponList couponListNew = new CouponList();
			couponListNew.setChannel(couponList.getChannel());
			couponListNew.setCouponCode(couponCode);
			couponListNew.setIssuerId(0);
			couponListNew.setCouponId(couponList.getCouponId());
			couponListNew.setOrderId(0);
			couponListNew.setUserId(couponList.getUserId());
			couponListNew.setStatus(CouponEnum.USE_STATUS_NOT.getCode());
			couponListNew.setInvalidTime(couponList.getInvalidTime());
			couponListNew.setCreateTime(System.currentTimeMillis() / 1000);
			couponListNew.setUpdateTime(System.currentTimeMillis() / 1000);
			couponListMapper.insert(couponListNew);
		});
	}

	/**
	 * 校验能否参与秒杀
	 *
	 * @author mjf
	 * @param buyGoods BuyGoodsValidate
	 * @return SeckillGoodsSku
	 */
	private SeckillGoodsSku __getSeckillGoodsSku(BuyGoodsValidate buyGoods) {
		// 秒杀活动
		SeckillActivity seckillActivity = seckillActivityMapper.selectOne(new QueryWrapper<SeckillActivity>()
				.eq("id", buyGoods.getSeckillId())
				.eq("status", SeckillEnum.STATUS_CONDUCT.getCode())
				.le("start_time", TimeUtils.timestamp())
				.ge("end_time", TimeUtils.timestamp())
				.eq("is_delete", 0)
				.last("limit 1"));

		Assert.notNull(seckillActivity, "秒杀活动已结束");

		SeckillGoodsSku seckillGoodsSku = seckillGoodsSkuMapper.selectOne(new QueryWrapper<SeckillGoodsSku>()
				.eq("seckill_id", buyGoods.getSeckillId())
				.eq("sku_id", buyGoods.getSkuId())
				.last("limit 1"));

		Assert.notNull(seckillGoodsSku, "秒杀商品信息不存在");

		if (seckillActivity.getLimitStatus() > 0 && buyGoods.getNum() > seckillActivity.getMaxBuy()) {
			throw new OperateException("单笔订单数量不能大于" + seckillActivity.getMaxBuy() + "件");
		}

		return seckillGoodsSku;
	}


	/**
	 * 判断购买商品之后是否赠送会员
	 * @param userId
	 * @param order
	 * @param orderGoodsList
	 */
	@Transactional
	public void receiveVip(Integer userId,Order order,List<OrderGoods> orderGoodsList){

		boolean falg = false;
		List<Integer> levelList = new ArrayList<>();
		List<Goods> goodsList = new ArrayList<>();
		Goods goods = new Goods();
		System.out.println("商品"+orderGoodsList.size());
		System.out.println("商品数量"+orderGoodsList.get(0).getGoodsNum());
		//判断商品是否存在赠送会员 并取最高等级会员
		for (OrderGoods orderGoods:orderGoodsList){
			goods = goodsMapper.selectById(orderGoods.getGoodsId());
			if(goods != null){
				//处理多个商品
				for(int i = 0;i<orderGoods.getGoodsNum();i++){
					goodsList.add(goods);
				}
				if(goods.getReceiveVip() != 0){
					falg = true;
					 levelList.add(goods.getReceiveVip());
				}
			}
		}
		if(falg){
			Integer level = levelList.stream().max(Integer::compareTo).get();
        	int maxLevelGoods = 0;
        	for(Goods goods1:goodsList){
    			if(goods1.getReceiveVip() == level){
    				maxLevelGoods += 1;
    			}
    		}
        	level = level+1;
			Distribution distribution = distributionMapper.selectOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getUserId, userId));
			distribution.setType(2);
			//原等级小于赠送等级则更新
			if(distribution.getLevelId() <= level){
				long currentTimeMillis = System.currentTimeMillis();
				long tenDigitTimestamp = currentTimeMillis / 1000;
				if(distribution.getExpireTime() == null){
					distribution.setExpireTime(tenDigitTimestamp);
				}
				//如果是同等级就在原有的基础上延长时间 如果升级就重新计算
				if(distribution.getLevelId() == level){
					Date date = new Date(distribution.getExpireTime() * 1000);
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(date); // 设置Calendar对象的时间为date
					calendar.add(Calendar.YEAR, maxLevelGoods);
					Date newDate = calendar.getTime();
					distribution.setExpireTime(newDate.getTime() / 1000);
				}else{
					Date date = new Date(currentTimeMillis);
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(date); // 设置Calendar对象的时间为date
					calendar.add(Calendar.YEAR, maxLevelGoods);
					Date newDate = calendar.getTime();
					distribution.setExpireTime(newDate.getTime() / 1000);
				}
				distribution.setLevelId(level);
				distributionMapper.updateById(distribution);


				VipRecord model = new VipRecord();
				model.setUserId(userId);
				model.setOrderSn(order.getOrderSn());
				model.setPayWay(0);
				model.setRelatedId(level);
				model.setOrderAmount(order.getPayMoney());
				model.setActualAmount(order.getPayMoney());
				model.setOrderCreateTime(order.getCreateTime());
				model.setOrderUpdateTime(order.getUpdateTime());
				model.setOrderStatus(1);
				model.setExtend(distribution.getExpireTime().toString());
				String remarl = "普通用户";
				switch (level) {
				case 2:
					remarl = "开通VIP(银牌会员)";
					break;
				case 3:
					remarl = "开通VIP(金牌会员)";
					break;
				case 4:
					remarl = "开通VIP(钻石会员)";
				case 5:
					remarl = "开通VIP(合伙人)";
				case 6:
					remarl = "开通VIP(联创V8)";
				case 7:
					remarl = "开通VIP(联创V9)";
					break;
				}
				model.setRemark(remarl);
				vipRecordMapper.insert(model);
			}
		}
	}

	/**
	 * 校验能都申请售后
	 *
	 * @author mjf
	 * @param userId Integer
	 * @param orderAfterValidate OrderAfterCreateValidate
	 */
	private void __checkAbleApplyOrderAfter(Integer userId,  OrderAfterCreateValidate orderAfterValidate) {
		Integer orderGoodsId = orderAfterValidate.getOrderGoodsId();
		BigDecimal refundMoney = orderAfterValidate.getRefundMoney();

		// 校验是否可以申请售后
		OrderGoods orderGoods = orderGoodsMapper.selectOne(new QueryWrapper<OrderGoods>()
				.eq("id", orderGoodsId)
				.eq("user_id", userId)
				.last("limit 1"));

		com.baomidou.mybatisplus.core.toolkit.Assert.notNull(orderGoods, "订单商品信息不存在");

		Order order = orderMapper.selectOne(new QueryWrapper<Order>()
				.eq("id", orderGoods.getOrderId())
				.last("limit 1"));

		com.baomidou.mybatisplus.core.toolkit.Assert.notNull(order, "订单信息不存在");

		// 可退款金额
		BigDecimal ableRefundMoney = orderGoods.getGoodsMoney().subtract(orderGoods.getCouponMoney());
		// 区分订单是否已发货
		if (order.getOrderStatus() == OrderEnum.ORDER_STATUS_WAIT_DELIVER.getCode()) {
			if (refundMoney.compareTo(ableRefundMoney.add(orderGoods.getExpressMoney())) > 0) {
				throw new OperateException("退款金额不可大于商品金额");
			}
		} else {
			if (refundMoney.compareTo(ableRefundMoney) > 0) {
				throw new OperateException("退款金额不可大于商品金额");
			}
		}

		// 订单-已完成 是否开启售后和已过售后时间
		if (order.getOrderStatus() == OrderEnum.ORDER_STATUS_COMPLETED.getCode()) {
			float afterSalesDay = Float.parseFloat(ConfigUtils.get("trade", "afterSalesDay", "-1"));
			// 售后已关闭
			if (afterSalesDay == -1) {
				throw new OperateException("系统已关闭售后维权");
			}
			// 确认收货后已过发起售后时间
			long afterSaleDeadline = (long) (afterSalesDay * 24 * 60 * 60) + order.getConfirmTime();
			if (TimeUtils.timestamp() > afterSaleDeadline) {
				throw new OperateException("订单已过售后时间，无法发起商品售后");
			}
		}

		// 订单-未支付,已取消,不可售后
		if (order.getOrderStatus() == OrderEnum.ORDER_STATUS_WAIT_PAY.getCode()
				|| order.getOrderStatus() == OrderEnum.ORDER_STATUS_CANCEL.getCode()) {
			throw new OperateException("当前订单商品不可申请售后");
		}

		// 校验是否已有售后记录 售后中或售后成功的
		OrderAfterGoods orderAfterGoods = orderAfterGoodsMapper.selectOne(new QueryWrapper<OrderAfterGoods>()
				.eq("order_goods_id", orderGoods.getId())
				.orderByDesc("id")
				.last("limit 1"));

		if (orderAfterGoods != null) {
			// 重新申请
			OrderAfter orderAfter = orderAfterMapper.selectOne(new QueryWrapper<OrderAfter>()
					.eq("order_id", orderAfterGoods.getOrderId())
					.orderByDesc("id")
					.last("limit 1"));

			// 重新申请售后时，售后状态需为售后中或已关闭
			if (orderAfter.getAfterStatus() == OrderAfterEnum.AFTER_STATUS_SUCCESS.getCode()) {
				throw new OperateException("已有售后成功记录，不可申请");
			}

			// 重新申请时，将旧的售后记录状态更新为售后关闭
			orderAfter.setAfterStatus(OrderAfterEnum.AFTER_STATUS_CLOSE.getCode());
			orderAfter.setSubStatus(OrderAfterEnum.SUB_STATUS_CLOSE_BUYER_CANCEL.getCode());
			orderAfterMapper.updateById(orderAfter);
		}
	}





}
